52

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"
1
  • 1
    I think you need the global replace option. And [0-9] can be simplified to \d. Commented Jul 4, 2012 at 11:39

5 Answers 5

102

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")
Sign up to request clarification or add additional context in comments.

3 Comments

How would I replaced them with a unicode character instead of X? For instance \U2022 ?
answer: replace(/[0-9]/g, '\u2022');
This works only if string has all digits. Doesn't work with "test123"
14

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

Comments

7

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

Comments

4

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

Comments

0

You forgot to add the global operator. Use this:

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

1 Comment

How does your answer differ from the accepted answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.