neila neila - 6 months ago 18
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);
alert(res);


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:
98+66-979

but I get
98+66-97,9


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

Answer

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"]

Comments