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"
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")
X? For instance \U2022 ?replace(/[0-9]/g, '\u2022');find the numbers and then replaced with strings which specified. It is achieved by two methods
Using a regular expression literal
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:
var s = "04.07.2012";
alert(s.replace(new RegExp("[0-9]","g"), "X"));
[0-9]can be simplified to\d.