在 JS 中,根据字符串前面的子字符串递增字符串中的数字



我需要在 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(next)
//Outputs '//localhost:3001/insight/page/3/'
//Needs to be '//localhost:3000/insight/page/3/'

下面是一个方便的代码笔:https://codepen.io/matt3224/pen/brrEQB?editors=1111

非常感谢

按@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/';
let next = link.replace(/d+(?=/$)/g, n => +n + 1);
console.log(next);

匹配page//之间的任何数字都应该有效,无论其他数字或它出现在 URL 中的哪个位置

let link = '//localhost:3000/insight/page/2/';
let next = link.replace(/page/(d+)//, (x,y) => 'page/' + (++y) + '/');
console.log(next)

test( '//localhost:3000/insight/page/2/' );
test( '//localhost:3000/insight/page/2/more/here' );
test( '//localhost:3000/page/2/' );
test( '//localhost:3000/insight/page/2/2/2/2/' );
function test(link) {
	var next = link.replace(/page/(d+)//, (x,y) => 'page/' + (++y) + '/');
	console.log(next)
}

搜索后跟一个数字page/,然后切出该数字,递增它,然后重建字符串。

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 做了同样的步骤要优雅得多,但也许我的回答会帮助人们看到发生了什么。

最新更新