views:

212

answers:

4

Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string.

var myString = 'abc123.8<blah>';

//desired output is 1238

Question: 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.

+1  A: 

Something along the lines of:

yourString = yourString.replace ( /[^0-9]/g, '' );
Jan Hančič
+3  A: 

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

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

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

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

I would use something very similar to what CMS posted. However, rather than manually complementing \d, I would use the built-in complement \D.

myString = myString.replace(/\D/g,'');
csj
Thanks csj; anyplace to find more info on `\D` ?
p.campbell
This is my default regex reference: http://www.regular-expressions.info/reference.htmlThe built-in character classes each have built-in complements.\d \D (digits versus everything but digits)\w \W (word charcters versus everything but word characters)\s \S (whitespace versus everything but whitespace)
csj