[javascript] 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"

This question is related to javascript regex

The answer is


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

The /g modifier is used to perform a global match (find all matches rather than stopping after the first)

You can use \d for digit, as it is shorter than [0-9].

JavaScript:

var s = "04.07.2012"; 
echo(s.replace(/\d/g, "X"));

Output:

XX.XX.XXXX

find the numbers and then replaced with strings which specified. It is achieved by two methods

  1. Using a regular expression literal

  2. Using keyword RegExp object

Using a regular expression literal:

<script type="text/javascript">

var string = "my contact number is 9545554545. my age is 27.";
alert(string.replace(/\d+/g, "XXX"));

</script>

**Output:**my contact number is XXX. my age is XXX.

for more details:

http://www.infinetsoft.com/Post/How-to-replace-number-with-string-in-JavaScript/1156


You forgot to add the global operator. Use this:

_x000D_
_x000D_
var s = "04.07.2012";_x000D_
alert(s.replace(new RegExp("[0-9]","g"), "X")); 
_x000D_
_x000D_
_x000D_