Selecting numbers in JavaScript string only
I want to select all digits from a given string. I tried with the code below, but it doesn't return all the numbers in the string:
var match = /\d+/.exec("+12 (345)-678.90[]");
console.log(match.toString());
It only returns 12
, while I expect it to return 1234567890
.
You need to use a flag global
, it will return you an array of consistent data that you can use join()
.
"+12 (345)-678.90[]".match(/\d+/g).join('');
simple implementation would be
var value='+12 (345)-678.90[]'.replace(/\D+/g, '');
console.log(value);
Use a global flag:
"+12 (345)-678.90[]".match(/\d+/g)
The pattern \d+
will only return sequential digits, and since you run exec
once without a parameter g
, it will give you the first occurrence of sequential digits.
Use this:
var re = /\d+/g;
var str = '+12 (345)-678.90[]';
var res = "";
while ((m = re.exec(str)) !== null) {
res += m[0];
}
alert(res);
Conclusion 1234567890
as we add the found digital sequences to the variable res
.