Keith L. Keith L. - 6 months ago 22
Javascript Question

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"

Answer

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