Increment a number in a string based on the substr

2019-03-02 03:16发布

问题:

I need to increment a number in a url, the number is always preceded by page/ so like page/2/ however the url could be constructed any which way and may even contain other numbers.

Here's what I have which works but increments all numbers rather than just the one that follows page/. What do I need to do to limit it to only the number preceded by 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/'

Here's a codepen for ease: https://codepen.io/matt3224/pen/brrEQB?editors=1111

Thanks so much

SOLUTION by @adeneo

let link = '//localhost:3000/insight/page/2/';
let next = link.replace(/page\/(\d+)\//, (x,y) => `page/${(++y)}/`);

回答1:

Matching any numbers between page/ and / should work, regardless of other numbers or where in the URL it occurs

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)
}



回答2:

You could look for a following slash and the end of the string and replace the number.

let link = '//localhost:3000/insight/page/2/';
let next = link.replace(/\d+(?=\/$)/g, n => +n + 1);

console.log(next);



回答3:

Search for page/ followed by a digit, then slice out the digit, increment it, and rebuild the string.

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
});`

As I was typing, adeneo did the same steps much more elegantly, but perhaps my answer will help someone see what's going on.