We can easily remove all non numbers from a string using JavaScript by making use of the JavaScript String replace() method along with the RegEx D metacharacter.

var someString = "This12 is34 5a st5ri6n7g with numbe88877777rs90.";

someString = someString.replace(/D/g, '');

console.log(someString);

#Output:
123455678887777790

Notice in the replace method above, that instead of using .replace(/D/, '') we use replace(/D/g, ''). If we used the expression /D/ in the replace function, it only replace the FIRST instance of a non number. Using the regular expression /D/g makes it so we replace ALL instances of a non number in the string.

Also notice that we make use of the RegEx D metacharacter, which matches all non-digit characters.


When using string variables in JavaScript, we can easily perform string manipulation to change the value of the string variables. One such manipulation is to remove all non numbers from a string variable.

The easiest way to get rid of non numbers in a string using JavaScript is with the JavaScript String replace() function.

The replace() function takes two arguments: the substring we want to replace, and the replacement substring. In this case, to remove non numbers, we use the D metacharacter (“/D/”) as the first argument and an empty string as the second argument.

Below is our example again of how you can remove non numbers from strings in JavaScript using the replace() function.

var someString = "This12 is34 5a st5ri6n7g with numbe88877777rs90.";

someString = someString.replace(/D/g, '');

console.log(someString);

#Output:
123455678887777790

Hopefully this article has been useful for you to learn how to remove non numbers from a string in JavaScript.

Categorized in:

JavaScript,

Last Update: May 3, 2024