968

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.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
p.campbell
  • 98,673
  • 67
  • 256
  • 322

12 Answers12

1941

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,'');
csj
  • 21,818
  • 2
  • 20
  • 26
  • 10
    Thanks csj; anyplace to find more info on `\D` ? – p.campbell Dec 07 '09 at 19:55
  • 43
    This is my default regex reference: http://www.regular-expressions.info/reference.html The 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 Dec 07 '09 at 20:38
  • 6
    Just to be clear, here is the syntax for replace: http://www.w3schools.com/jsref/jsref_obj_regexp.asp because the forward slashes and the "g" are part of that command, not part of the RegEx. – Mike K Feb 09 '11 at 00:17
  • 2
    does `replace` work with this exact syntax in all browsers? seems like I remember getting an `object has no method 'replace' ` in an older version of IE when using this with text I grabbed with jQuery... or something like that. – cwd Feb 07 '13 at 21:39
  • 2
    @cwd I have no idea what has been supported in past or current browsers. The question specified a non-DOM context, so it's likely that the poster was scripting in a non web browser environment. – csj Feb 25 '13 at 23:15
  • 1
    Great tool to test regular expression online (It's not mine :)). https://regex101.com – Madura Pradeep May 03 '16 at 10:24
  • 1
    i tried following but nothing worked "this.value = this.value.replace(eval(!/^[A-Za-z\d.#-,]$/),'')" "this.value = this.value.replace(eval(/^[A-Za-z\d.#-,]$/),'')" "this.value = this.value.replace(eval(specialCharRegex),'')" what should i do? – Zaveed Abbasi Feb 16 '18 at 16:31
  • 1
    You can use `String(myString).replace(/\D/g,'')` in case they pass only a number this code won't throw an error. – brycejl May 13 '20 at 05:18
  • 1
    this works fine for positive integers but goodbye negative numbers. – skilleo Aug 23 '21 at 21:54
  • 2
    This turns `1.2` into `12` – adamdport Feb 09 '22 at 15:02
  • @skilleo fair enough, but the OP did eventually edit their question to indicate that they were seeking to preserve the digits themselves. 0-9 – csj Apr 06 '22 at 21:39
  • @adamdport The OP's example specifically shows a period being stripped away. – csj Apr 06 '22 at 21:40
472

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

var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"
max4ever
  • 11,909
  • 13
  • 77
  • 115
81

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

myString.replace(/[^0-9]/g, '');
Auraseer
  • 1,245
  • 8
  • 14
36

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

var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
32

Something along the lines of:

yourString = yourString.replace ( /[^0-9]/g, '' );
Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
  • 18
    Not exactly an answer to the original question, but a version to handle the decimal point: `yourString = yourString.replace ( /[^0-9.]/g, '' );` – Maxim Mai Jul 05 '16 at 17:26
  • 1
    Late to the party but also need dash and comma. In certain regions decimal is done with a comma: `replace(/[^0-9.,-]/g, ''` – Abdul Sadik Yalcin Mar 19 '22 at 00:12
29

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));
jackosaur
  • 285
  • 4
  • 6
4

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>
Grant
  • 5,709
  • 2
  • 38
  • 50
4

The problem with these answers above, is that it assumes whole numbers. But if you need a floating point value, then the previous reg string will remove the decimal point.

To correct this you need write a negated character class with ^

var mystring = mystring.replace(/[^0-9.]/g, '');
Debbie Kurth
  • 403
  • 3
  • 16
2

try

myString.match(/\d/g).join``

var myString = 'abc123.8<blah>'
console.log( myString.match(/\d/g).join`` );
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
2

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('');
Chaos Legion
  • 2,730
  • 1
  • 15
  • 14
1

This,

.match(/\d|\.|\-/g).join('');

Handles both , and . also -

Example:

"Balance -$100,00.50".match(/\d|\.|\-/g).join('');

Outputs

-10000.50

Andrea Lazzarotto
  • 2,471
  • 1
  • 22
  • 38
jeffbRTC
  • 1,941
  • 10
  • 29
-6

we are in 2017 now you can also use ES2016

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

or

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

The result is

1238
Frank Wisniewski
  • 1,182
  • 8
  • 7
  • 14
    This is a very inefficient way to go about this operation. – djheru Aug 10 '17 at 16:02
  • 6
    It converts the string into an array of single-character strings via a spare method, and then applies filter function over JavaScript on each array item, returning a new string array, to finally join that array back into a string. Regex takes a string and returns a string and the processing is done via native code. – ShortFuse Dec 18 '18 at 23:03