Khadim Ali
Khadim Ali

Reputation: 2598

Selecting numbers only in a JavaScript string

I want to select all the digits from a given string. I tried with the code below, but it does not 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.

Upvotes: 3

Views: 313

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627536

The \d+ pattern will return consecutive digits only, and since you running exec once without g option, it will only give you the first occurrence of consecutive 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);

Output is 1234567890, as we append found digit sequences to the res variable.

Upvotes: 1

divakar
divakar

Reputation: 1379

simple implementation will be

var value='+12 (345)-678.90[]'.replace(/\D+/g, '');
console.log(value);

Upvotes: 5

Satpal
Satpal

Reputation: 133453

You need to use global flag, it will return you an array of matched data the you can use join() it.

"+12 (345)-678.90[]".match(/\d+/g).join('');

alert("+12 (345)-678.90[]".match(/\d+/g).join(''))

Upvotes: 2

moonwave99
moonwave99

Reputation: 22820

Use the global flag:

"+12 (345)-678.90[]".match(/\d+/g)

Upvotes: 1

Related Questions