Increment a number in a string in with regex

前端 未结 4 938
说谎
说谎 2020-11-28 13:15

I get the name of an input element, which is a string with a number (url1). I want to increment the number by 1 (url2

4条回答
  •  旧时难觅i
    2020-11-28 13:35

    Simple. Use a substitution function with regular expressions:

    s = 'abc99abc';
    s = s.replace(/\d+/, function(val) { return parseInt(val)+1; });
    

    will set variable s to: abc100abc

    But it gets more complicated if you want to make sure you only change a certain parameter in the URL:

    s = '?foo=10&bar=99';
    s = s.replace(/[&?]bar=\d+/, function(attr) {
      return attr.replace(/\d+/, function(val) { return parseInt(val)+1; });
    });
    

    will set variable s to: ?foo=10&bar=100

提交回复
热议问题