Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 677
p.campbell Avatar asked Dec 07 '09 18:12

p.campbell


People also ask

How do I remove non numeric characters from a string?

In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.

How do I remove a character from a number string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do you remove all occurrences of a character from a string in JavaScript?

Delete all occurrences of a character in javascript string using replaceAll() The replaceAll() method in javascript replaces all the occurrences of a particular character or string in the calling string. The first argument: is the character or the string to be searched within the calling string and replaced.


2 Answers

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,''); 
like image 173
csj Avatar answered Sep 24 '22 18:09

csj


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

var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50" 
like image 36
max4ever Avatar answered Sep 25 '22 18:09

max4ever