JS regex replace number

Trying to make me think of some regex using JS.replace to replace an integer with a string.

For example, a string might be:

var string = 'image[testing][hello][0][welcome]'; 

I want to replace "0" with another value. I originally used this:

 string.replace( /\[\d\]/g, '[newvalue]'); 

But when we start replacing double digits or more (12, 200, 3204, you understand what I mean), it stops working normally. Not sure how to make it work the way I want it.

Thanks in advance. Very much appreciated.

+6
source share
2 answers

You need to specify a few numbers:

 string.replace( /\[\d+\]/g, '[newvalue]'); 

JS Fiddle demo

(Note that the demo uses jQuery to iterate over the nodes, but it's just a convenience and has nothing to do with the regex, it just demonstrates its function.)

The reason your original didn't work, in my opinion, was because \d matches only one digit, while the operator / character + sets the character of the previous (in this case) one or more times.

Link:

+11
source

Use the following:

string.replace( /\[\d+\]/g, '[newvalue]');

This should match all the numbers in parentheses.

+3
source

Source: https://habr.com/ru/post/921723/


All Articles