Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS regex replace number

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.

like image 216
Matthew Ruddy Avatar asked Jul 30 '12 22:07

Matthew Ruddy


People also ask

How do I replace a number in a string?

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.

Can regex replace characters?

RegEx can be effectively used to recreate patterns. So combining this with . replace means we can replace patterns and not just exact characters.

How can I extract a number from a string in JavaScript?

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+)/).


1 Answers

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:

  • JavaScript Regular Expressions, at the Mozilla Developer Network.
like image 150
David Thomas Avatar answered Sep 28 '22 19:09

David Thomas