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

.

+3


source to share


4 answers


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('');

      



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

Run codeHide result


+2


source


simple implementation would be



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

      

+5


source


Use a global flag:

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

      

+1


source


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);
      

Run codeHide result


Conclusion 1234567890

as we add the found digital sequences to the variable res

.

+1


source







All Articles