learningcoding
learningcoding

Reputation: 197

Regex - matching only digits, excluding special characters - doesn't work

I am trying out reggae and was trying to remove the special characters like parentheses, brackets etc. from a phone number. Instead of getting the first 3 digits (which I intended), I am getting this [ '201', index: 0, input: '2014447777' ] Why is this happening?

 function numbers(num){
 return num.replace(/[^0-9]/g, "").match(/\d\d\d/);

}
numbers("(347)4448888");

Upvotes: 0

Views: 52

Answers (1)

Tushar
Tushar

Reputation: 87203

String#match returns

An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.

To get first three digits, use

return num.replace(/\D+/g, '').match(/\d{3}/)[0];
                    ^^^               ^^^^^  ^^^   : Match all non-digits
                                      ^^^^^  ^^^   : Match three digits and returns digits from the array.

Upvotes: 3

Related Questions