3

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.

3
  • 2
    use global in regex. Commented May 27, 2015 at 11:54
  • 1
    You're only selecting one match. There are four matches in there. "+12 (345)-678.90[]".replace(/\D/g, ""); should do it Commented May 27, 2015 at 11:54
  • 2
    Try something like /\d+/g. Commented May 27, 2015 at 11:57

4 Answers 4

5

simple implementation will be

var value='+12 (345)-678.90[]'.replace(/\D+/g, '');
console.log(value);
Sign up to request clarification or add additional context in comments.

Comments

2

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

1

Use the global flag:

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

1 Comment

This was returning the matches with , .. like 12,345,678,90. Adding .join('') returned perfectly was required. :)
1

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.

1 Comment

@Juhana: Good catch, looks like it is redundant here. There are cases when we need to count matches, and then it is useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.