Strip all non-numeric characters from string in JavaScript

Strip all non-numeric characters from string in JavaScript

Consider a non-DOM scenario where you’d want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range 0 – 9 should be kept.
var myString = ‘abc123.8‘;

//desired output is 1238

How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren’t suitable.

Solutions/Answers:

Solution 1:

Use the string’s .replace method with a regex of \D, which is a shorthand character class that matches all non-digits:

myString = myString.replace(/\D/g,'');

Solution 2:

If you need this to leave the dot for float numbers, use this

var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"

Solution 3:

Use a regular expression, if your script implementation supports them. Something like:

myString.replace(/[^0-9]/g, '');

Solution 4:

You can use a RegExp to replace all the non-digit characters:

var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238

Solution 5:

Something along the lines of:

yourString = yourString.replace ( /[^0-9]/g, '' );

Solution 6:

try

myString.match(/\d/g).join('')
var myString = 'abc123.8<blah>'
console.log( myString.match(/\d/g).join('') );