neila neila - 5 months ago 14
Javascript Question

javascript getting a faulty result using a regular expression

In my web page, I have:

var res = number.match(/[0-9\+\-\(\)\s]+/g);

As you can see, I want to get only numbers, the characters +, -, (, ) and the space(\s)

When I tried
number = '98+66-97fffg9'
, the expected result is:

but I get

the comma is an odd character here! How can eliminate it?


As per documents from docs, the return value is

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

S,your return value contains

["98+66-97", "9"]

So if you want to skip parentheses-captured matched results

just remove g flag from regular expression.

So,your expression should like this one

number.match(/[0-9\+\-\(\)\s]+/); which gives result ["98+66-97"]