Advertisement
Advertisement


Strip all non-numeric characters from string in JavaScript


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.

2019/04/24
1
729
4/24/2019 10:32:54 AM

Accepted 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,'');
2014/12/01
1483
12/1/2014 7:56:46 PM


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

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

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

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

Something along the lines of:

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

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';
console.log(parseNum(str));

2020/05/28

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>
2020/01/30

Source: https://stackoverflow.com/questions/1862130
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]