Strip all non-numeric characters from string in JavaScript
Asked Answered
M

12

992

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.

Magistrate answered 7/12, 2009 at 18:59 Comment(0)
G
1976

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,'');
Gynaeco answered 7/12, 2009 at 19:14 Comment(12)
Thanks csj; anyplace to find more info on \D ?Magistrate
This is my default regex reference: 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)Gynaeco
Just to be clear, here is the syntax for replace: w3schools.com/jsref/jsref_obj_regexp.asp because the forward slashes and the "g" are part of that command, not part of the RegEx.Barina
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.Induplicate
@Induplicate 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.Gynaeco
Great tool to test regular expression online (It's not mine :)). regex101.comBonnybonnyclabber
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?Hawkins
You can use String(myString).replace(/\D/g,'') in case they pass only a number this code won't throw an error.Shaner
this works fine for positive integers but goodbye negative numbers.Throne
This turns 1.2 into 12Skippie
@Throne fair enough, but the OP did eventually edit their question to indicate that they were seeking to preserve the digits themselves. 0-9Gynaeco
@Skippie The OP's example specifically shows a period being stripped away.Gynaeco
K
478

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

var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"
Klos answered 23/2, 2012 at 9:5 Comment(12)
Any regexp experts? How to make this allow only a single dot (very relevant with numbers). Thanks!Vulvitis
what do you mean? give input and output exampleKlos
I mean, it currently accepts for example "1..56" and "1.5.28", right? Is it possible to make it accept only numbers with a single dot, such as "1.56"?Vulvitis
use https://mcmap.net/q/54381/-regex-to-check-whether-a-string-contains-only-numbers-duplicate to test it like this: new RegExp(/^-?\d+\.?\d*$/).test("1.5.28")Klos
Is that possible to change all , by . in your regex? In some countries, the comma is used as a separator instead of the point. :)Batten
@Batten it is, but be aware, in such cases there is possibilty they are both there (Eg. 1,000,000.5) - so you should rather do .replace(/",","."/g) first :)Gullett
@Klos Whats with the "-" in the regexp?Gullett
Not good: "aaa 2.9px of bbb.".replace(/[^\d.-]/g, '')2.9. Should strip any String which might surround a Number..Dipietro
Great test! my first idea is [^\d.-]+[^\d]+ should work in this caseKlos
@Klos you saved my life, thanks for handling -(negative) number case :)Ethylethylate
@Vulvitis perhaps: parseFloat("-1234.5.50 €".replace(/[^\d.-]/g, ''))Apul
Great answer, if you want a numeric field you mean any number event floats :)Eventempered
H
82

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

myString.replace(/[^0-9]/g, '');
Homicidal answered 7/12, 2009 at 19:3 Comment(5)
For some reason this way seems much more readable than [^\d].Menke
whats the g for after the regex delimiter??Platonism
@NativeCoder #12994129Guthrie
will not work for float/decimal values for example, "7.6$" will return 76Find
like @SikandarTariq mentioned but also negative values.Throne
H
39

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

var myString = 'abc123.8<blah>';
myString = myString.replace(/[^\d]/g, ''); // 1238
Holler answered 7/12, 2009 at 19:2 Comment(0)
S
35

Something along the lines of:

yourString = yourString.replace ( /[^0-9]/g, '' );
Subset answered 7/12, 2009 at 19:1 Comment(2)
Not exactly an answer to the original question, but a version to handle the decimal point: yourString = yourString.replace ( /[^0-9.]/g, '' );Antimagnetic
Late to the party but also need dash and comma. In certain regions decimal is done with a comma: replace(/[^0-9.,-]/g, ''Hallucinogen
C
33

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));
Candelariacandelario answered 28/5, 2020 at 0:15 Comment(4)
For me, this is better than the accepted answer, because it keeps the decimal.Morey
You might want to add "-" as well because the number can be negative as well.Makebelieve
...but only if - is the first characterRhizomorphous
this does WRONG for the input my text: 9123.11, okay.?Solvent
L
7

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, '');
Lynnett answered 12/6, 2022 at 21:16 Comment(1)
this does WRONG for the input my text: 9123.11 okay.Solvent
S
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>
Sabir answered 30/1, 2020 at 15:3 Comment(0)
B
3

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('');
Bluebeard answered 26/5, 2020 at 7:16 Comment(0)
G
2

try

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

var myString = 'abc123.8<blah>'
console.log( myString.match(/\d/g).join`` );
Gluey answered 24/4, 2019 at 10:30 Comment(5)
how does this work?Platelet
@Platelet match will filter all digits and put them into array, join will glue array elements into single stringMegagamete
i meant the join with the backticks. what's going on there?Platelet
@Platelet read about: js tagged templatesMegagamete
Yeah I've seen tagged templates, just don't understand what is going on with join using them. Is this just saving two characters, invoking join with a single argument ""?Platelet
K
1

This,

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

Handles both , and . also -

Example:

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

Outputs

-10000.50

Kisner answered 21/11, 2021 at 0:43 Comment(0)
P
-5

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
Planetstruck answered 9/7, 2017 at 9:4 Comment(2)
This is a very inefficient way to go about this operation.Cann
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.Stinkpot

© 2022 - 2024 — McMap. All rights reserved.