简体   繁体   中英

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?

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); 

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM