1

I have a long string where I need to increment every number within it, leaving the rest of the text as it is.

I'm using this function

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

Which works great on numbers that are in free text but fails when the numbers are surrounded by square brackets. Example:

<input id="Form[0]_Phone" name="Form[0].Phone" type="text" value="">

Needs to become

<input id="Form[1]_Phone" name="Form[1].Phone" type="text" value="">

I've used this example to try and help, and I've tried a few variations but my regex skills have failed me.

Any assistance much appreciated.

Community
  • 1
  • 1
Tom Styles
  • 1,098
  • 9
  • 20

2 Answers2

2

You need to use 'global' flag, then it should replace all occurences.

i.e.

newHtml = newHtml.replace(/\d+/g, function (val) { return parseInt(val) + 1; });

See it working here: http://jsfiddle.net/4S7CE/

Without 'g', it would replace only first instance of the match.

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
2

There is nothing in your pattern causing the described behaviour - numbers in square brackets should also be affected. One obvious issue is you're affecting only the first number found, not all - add the g global flag after the closing forward slash of the pattern.

Works for me - see this Fiddle: http://jsfiddle.net/ypUmg/

Mitya
  • 33,629
  • 9
  • 60
  • 107