Increment a number in a string based on the substring before it in JS

前端 未结 3 1372
独厮守ぢ
独厮守ぢ 2021-01-26 20:31

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 ma

3条回答
  •  死守一世寂寞
    2021-01-26 20:43

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

提交回复
热议问题