Keith L.
Keith L.

Reputation: 2124

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"

Upvotes: 52

Views: 158687

Answers (5)

coder
coder

Reputation: 73

You forgot to add the global operator. Use this:

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

Upvotes: 0

Mohamed Rasik
Mohamed Rasik

Reputation: 168

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

Upvotes: 7

Ωmega
Ωmega

Reputation: 43673

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

Upvotes: 4

Gustav Barkefors
Gustav Barkefors

Reputation: 5086

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

Upvotes: 102

Joey
Joey

Reputation: 354426

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

Upvotes: 14

Related Questions