Keith L. Keith L. - 1 year ago 261
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 Source

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")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download