替换javascript或jQuery中的斜杠和数字
我搜索了stackoverflow,但找到了一个可以复制的解决方案 我被一个url刺痛了,比如: 职位编号可以是随机的([0-9])。 现在,我想把“post/1/”改为“newpost/2/” 如何使用javascript或jQuery实现这一点 我尝试了.replace函数,但不知道如何组合字符 提前感谢试试看替换javascript或jQuery中的斜杠和数字,javascript,jquery,Javascript,Jquery,我搜索了stackoverflow,但找到了一个可以复制的解决方案 我被一个url刺痛了,比如: 职位编号可以是随机的([0-9])。 现在,我想把“post/1/”改为“newpost/2/” 如何使用javascript或jQuery实现这一点 我尝试了.replace函数,但不知道如何组合字符 提前感谢试试看 var old=”http://localhost:8888/mypage/post/1/"; var new=old.replace(“post/1/”,“newpost/2/”
var old=”http://localhost:8888/mypage/post/1/";
var new=old.replace(“post/1/”,“newpost/2/”;
控制台日志(新)代码>
此日志记录为“”
如果post后的数字是动态的,请根据该数字创建新字符串,然后尝试使用replace函数 试试看
var old=”http://localhost:8888/mypage/post/1/";
var new=old.replace(“post/1/”,“newpost/2/”;
控制台日志(新)代码>
此日志记录为“”
如果post后的数字是动态的,请根据该数字创建新字符串,然后尝试使用replace函数 您可以使用JavaScript字符串方法:
var url='1〕http://localhost:8888/mypage/post/1/';
var newUrl=url.replace(/post\/([0-9])\/,“newpost/$1/”;
console.log(newUrl)代码>您可以使用JavaScript字符串方法:
var url='1〕http://localhost:8888/mypage/post/1/';
var newUrl=url.replace(/post\/([0-9])\/,“newpost/$1/”;
console.log(newUrl)代码>我认为这应该可以做到:
var url = 'http://localhost:8888/mypage/post/5/';
// increase number by 1
var number = url.match(/post\/([0-9]+)\//, 'newpost/$1/');
number = parseInt(number[1]);
number++;
// replace matches in string
var newUrl = url.replace(/post\/([0-9])\//, 'newpost/' + number + '/');
console.log(newUrl);
我认为这应该起作用:
var url = 'http://localhost:8888/mypage/post/5/';
// increase number by 1
var number = url.match(/post\/([0-9]+)\//, 'newpost/$1/');
number = parseInt(number[1]);
number++;
// replace matches in string
var newUrl = url.replace(/post\/([0-9])\//, 'newpost/' + number + '/');
console.log(newUrl);
如果需要更多控制,则可以将字符串拆分为数组并编辑单个值,然后转换回字符串:
var url = 'http://localhost:8888/mypage/post/1/';
var urlArray = url.split("/");
urlArray[4] = "newpost";
urlArray[5] = "2"; // will also work with a number
var newUrl = urlArray.join("/");
如果需要更多控制,则可以将字符串拆分为数组并编辑单个值,然后转换回字符串:
var url = 'http://localhost:8888/mypage/post/1/';
var urlArray = url.split("/");
urlArray[4] = "newpost";
urlArray[5] = "2"; // will also work with a number
var newUrl = urlArray.join("/");
你是想把post/
之后的数字改成post/
还是把newpost
改成newpost
?基本上这只是数字,但我想确定它是post/
+随机数的组合,而不是url中可能出现的任何数字。我注意到了一些事情。您是否建议将1
更改为2
?我们要假设他们是加一还是乘二?Daerik已经给了麻省理工学院一个合适的答案。我需要在当前帖子编号上添加1(++)。您是想只更改post/
之后的编号,还是想将post
更改为newpost
?基本上这只是个编号,但是我想确保它是post/
+随机数
的组合,而不是url中可能出现的任何数字。我只是注意到了一些东西。您是否建议将1
更改为2
?我们要假设他们是加一还是乘二?Daerik已经给了麻省理工学院一个合适的答案。我需要在当前的帖子号上加1(++)。谢谢你的回答。我有一个后续问题:newpost/$1/
中的$
在做什么?([0-9])
但是应该改为:([0-9]+)
两位数(10,11,12…$n
($1
)是一种在括号内标识规则并允许从原始字符串中提取规则以用于输出字符串的方法。如果您有多个paren(()
)组,则可以使用$2
,$3
,etc@simey.me非常同意,但OP特别要求([0-9])
。在没有进一步说明的情况下,我假设它是一个0到9范围内的单个数字。谢谢你的回答。我有一个后续问题:newpost/$1/
中的$
在做什么?([0-9])
但是应该改为:([0-9]+)
两位数(10,11,12…$n
($1
)是一种在括号内标识规则并允许从原始字符串中提取规则以用于输出字符串的方法。如果您有多个paren(()
)组,则可以使用$2
,$3
,etc@simey.me非常同意,但OP特别要求([0-9])
。在没有进一步说明的情况下,我假设它是一个0到9范围内的单个数字。