Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS regex: replace all digits in string

I need to replace all digits.

My function only replaces the first digit.

var s = "04.07.2012"; alert(s.replace(new RegExp("[0-9]"), "X")); // returns "X4.07.2012"                                             // should be XX.XX.XXXX" 
like image 796
Keith L. Avatar asked Jul 04 '12 11:07

Keith L.


People also ask

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. For more information about numbered capturing groups, see Grouping Constructs.

Is there a Replace All in JavaScript?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

How do I remove a character from a number string?

Using 'str. Using str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str.


2 Answers

You need to add the "global" flag to your regex:

s.replace(new RegExp("[0-9]", "g"), "X") 

or, perhaps prettier, using the built-in literal regexp syntax:

.replace(/[0-9]/g, "X") 
like image 133
Gustav Barkefors Avatar answered Oct 07 '22 23:10

Gustav Barkefors


Use

s.replace(/\d/g, "X") 

which will replace all occurrences. The g means global match and thus will not stop matching after the first occurrence.

Or to stay with your RegExp constructor:

s.replace(new RegExp("\\d", "g"), "X") 
like image 36
Joey Avatar answered Oct 07 '22 23:10

Joey