[Solved] 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<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.

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

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"
Respondent: max4ever

Solution #3:

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

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

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, '' );
Respondent: Jan Hančič

Solution #6:

Short function to remove all non-numeric characters but keep the decimal (and return the number):

parseNum = str => +str.replace(/[^.d]/g, '');
let str = 'a1b2c.d3e';

Respondent: jackosaur

Solution #7:

Unfortunately none of the answers above worked for me.

I was looking to convert currency numbers from strings like $123,232,122.11 (1232332122.11) or USD 123,122.892 (123122.892) or any currency like ₹ 98,79,112.50 (9879112.5) to give me a number output including the decimal pointer.

Had to make my own regex which looks something like this:

str = str.match(/d|./g).join('');
Respondent: Chaos Legion

Solution #8:

In Angular / Ionic / VueJS — I just came up with a simple method of:

stripNaN(txt: any) {
    return txt.toString().replace(/[^a-zA-Z0-9]/g, "");

Usage on the view:

<a [href]="'tel:'+stripNaN(single.meta['phone'])" [innerHTML]="stripNaN(single.meta['phone'])"></a>
Respondent: Grant

Solution #9:



Solution #10:

we are in 2017 now you can also use ES2016

var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));


console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));  

The result is

Respondent: Frank Wisniewski

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.