Trying to get my head around some regex using JS .replace to replace an integer with a string.
For example, the string could be:
var string = 'image[testing][hello][0][welcome]';
I want to replace the '0' with another value. I was originally using this:
string.replace( /\[\d\]/g, '[newvalue]');
But when we start replacing double digits or more (12, 200, 3204, you get what I mean), it stops working properly. Not sure how to get it functioning the way I want it too.
Thanks in advance. Greatly appreciated.
To replace all numbers in a string, call the replace() method, passing it a regular expression that globally matches all numbers as the first parameter and the replacement string as the second. The replace method will return a new string with all matches replaced by the provided replacement.
RegEx can be effectively used to recreate patterns. So combining this with . replace means we can replace patterns and not just exact characters.
The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).
You need to specify multiple digits:
string.replace( /\[\d+\]/g, '[newvalue]');
JS Fiddle demo
(Note the demo uses jQuery to iterate through the nodes, but it's merely a convenience, and has no bearing on the regular expression, it just demonstrates its function.)
The reason your original didn't work, I think, was because \d
matches only a single digit, whereas the +
operator/character specifies the preceding (in this case digit) character one or more times.
Reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With