简体   繁体   中英

How to increment a number within square brackets in Javascript

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.

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

ie

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM