Khadim Ali Khadim Ali - 6 months ago 11
jQuery Question

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
.

Answer

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

Comments