Javascript 根据JS中字符串前面的子字符串,增加字符串中的数字
我需要在url中增加一个数字,这个数字前面总是有Javascript 根据JS中字符串前面的子字符串,增加字符串中的数字,javascript,replace,Javascript,Replace,我需要在url中增加一个数字,这个数字前面总是有page/,就像page/2/一样,但是url可以以任何方式构造,甚至可能包含其他数字 以下是我所拥有的功能,它可以增加所有数字,而不仅仅是page/后面的数字。我需要做什么才能将其限制为前面有page/的数字 let link = '//localhost:3000/insight/page/2/'; let next = link.replace(/\d+/g, function(n){ return ++n }); console.log(
page/
,就像page/2/
一样,但是url可以以任何方式构造,甚至可能包含其他数字
以下是我所拥有的功能,它可以增加所有数字,而不仅仅是page/
后面的数字。我需要做什么才能将其限制为前面有page/
的数字
let link = '//localhost:3000/insight/page/2/';
let next = link.replace(/\d+/g, function(n){ return ++n });
console.log(next)
//Outputs '//localhost:3001/insight/page/3/'
//Needs to be '//localhost:3000/insight/page/3/'
这里有一个代码笔,方便您使用:
非常感谢
@adeneo的解决方案
let link = '//localhost:3000/insight/page/2/';
let next = link.replace(/page\/(\d+)\//, (x,y) => `page/${(++y)}/`);
您可以查找下面的斜杠和字符串的结尾,然后替换数字
let link='//localhost:3000/insight/page/2/;
让next=link.replace(/\d+(?=\/$)/g,n=>+n+1);
console.log(下一步)代码>您可以查找下面的斜杠和字符串的结尾,并替换数字
let link='//localhost:3000/insight/page/2/;
让next=link.replace(/\d+(?=\/$)/g,n=>+n+1);
console.log(下一步)代码>匹配page/
和/
之间的任何数字都应该有效,而不管其他数字或它出现在URL中的什么位置
let link='//localhost:3000/insight/page/2/;
让next=link.replace(/page\/(\d+)\/,(x,y)=>“page/”+(++y)+“/”);
console.log(下一步)
匹配页面/
和/
之间的任何数字都应该有效,而不管其他数字或它出现在URL中的什么位置
let link='//localhost:3000/insight/page/2/;
让next=link.replace(/page\/(\d+)\/,(x,y)=>“page/”+(++y)+“/”);
console.log(下一步)
搜索页面/
,后跟一个数字,然后切掉数字,增加数字,重新生成字符串
let next = link.replace(/page\/\d+/g, function(n){
let num = parseInt(n.slice(5))
num++
console.log(num)
const result = "page/"+num
return result
});`
在我打字的时候,adeneo同样的步骤做得非常优雅,但也许我的回答会帮助别人看到发生了什么。搜索页面/
,然后再搜索一个数字,然后切掉数字,增加数字,重新生成字符串
let next = link.replace(/page\/\d+/g, function(n){
let num = parseInt(n.slice(5))
num++
console.log(num)
const result = "page/"+num
return result
});`
在我打字时,adeneo以更优雅的方式完成了相同的步骤,但也许我的回答会帮助别人看到发生了什么。这看起来不错,但我也不能限制到字符串的末尾,您也有哪些版本?或者你喜欢搜索页面和下面的数字吗?这看起来不错,但是我也不能限制到字符串的末尾,你也有哪些版本?或者您想搜索页面和以下号码吗?这是totes!我做了一点小小的改变,但这是我要用的,非常感谢你这是手提包!我做了一点小改动,但这是我要用的,非常感谢