How To Replace All Numbers In A String Using JavaScript

Replace all Numbers in a String using JavaScript

The Replace() function in Javascript often replaces strings at will. So today, I will share with you how to replace all numbers in a string using Javascript with the replace() method.

Replace all numbers in a string using JavaScript

Using the replace() function in Javascript is the first thing that comes to mind when changing all the numbers in the string. The replace() function is used when searching and replacing a substring or a regular expression in the parent string. This method does not change the parent string but returns a new string. To understand the syntax, you can read here.

If the substring is not expressed as a regular expression, replace() will only replace the first substring found. If you want to find and replace all, you can use /string/g.

Using the RegExp() constructor

You want to search all numbers in a string to replace. We use the regular expression representing numbers from 0 to 9 as [0-9].

The first way to use the RegExp() constructor is to call a new RedExp() function.

Code sample:

let str1 = 'My name is Junie. I am 20 years old';
let newStr1 = str1.replace(new RegExp("[0-9]", "g"), "@");


My name is Junie. I am @@ years old

All numbers in the string have been replaced by the @ character in the second argument of the replace() function.

Create regular expression

The second way of using a regular expression is that we just need to create a regular expression that includes a pattern between the slash /.

You can replace all numbers in any strings by changing the second argument of replace() function. For example, replace it with the character x.

Code sample:

let str2 = 'My number is 813892';
let newStr2 = str2.replace(/[0-9]/g, "x");


My number is xxxxxx

In the above ways, we have used brackets [0-9] to find the numbers in the string, and in addition, we have the second way to use the \d notation.

Code sample:

let str3 = '18 hours 40 minutes 27 millisecond';
let newStr3 = str3.replace(/\d/g, "?");


?? hours ?? minutes ?? millisecond


I showed you how to replace all numbers in a string using JavaScript. With the first method of creating the RegEx() object, the regular expressions will translate the regular expressions at program execution, so the performance is not as good as with using the pure regular descriptor. But the most significant advantage of it is that we can change it. So in many problems that need to change a lot, we can use it. But the second way makes it easier to write and remember longer. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *