Strip all non-numeric characters from string in JavaScript – Dev

The best answers to the question “Strip all non-numeric characters from string in JavaScript” in the category Dev.

QUESTION:

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<blah>';

//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.

ANSWER:

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

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

ANSWER:

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,'');

ANSWER:

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

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

ANSWER:

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

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