senior
senior

Reputation: 2266

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?

Upvotes: 0

Views: 79

Answers (5)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

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

Upvotes: 1

Darek
Darek

Reputation: 570

Its probably because you get two groups that satisfied your expression.

In other words: match mechanism stops aggregating group when it finds first unwanted character -f. Then it skips matching until next proper group that, in this case, contains only one number - 9. This two groups are separated by comma.

Try this:

var number = '98+66-97fffg9';
var res = number.match(/[0-9\+\-\(\)\s]+/g);  
// res is an array! You have to join elements!
var joined = res.join('');
alert(joined);

Upvotes: 2

maulik sakhare
maulik sakhare

Reputation: 2037

stringvariable.match(/[0-9\+\-\(\)\s]+/g); will give you output of matching strings from stringvariable excluding unmatching characters.

In your case your string is 98+66-97fffg9 so as per the regular expression it will eliminate "fffg" and will give you array of ["98+66-97","9"]. Its default behavior of match function.

You can simply do res.join('') to get the required output. Hope it helps you

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

String.match returns an array of matched items. In your case you have received two items ['98+66-97','9'], but alert function outputs them as one string '98+66-97,9'.
Instead of match function use String.replace function to remove(filter) all unallowable characters from input number:

var number = '98+66-97fffg9',
    res = number.replace(/[^0-9\+\-\(\)\s]+/g, "");

console.log(res);   // 98+66-979

Upvotes: 1

yelsayed
yelsayed

Reputation: 5532

You're getting this because your regex matched two results in the number string, not one. Try printing res, you'll see that you've matched both 98+66-979 as well as 9

Upvotes: 1

Related Questions