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"
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.
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.
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.
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")
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")
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