1

here's the code:

reg = /(\d{3}\.){3}\d{3}/;
var str8 = "111.222.333.444";
console.log(str8.match(reg));

the result:Array [ "111.222.333.444", "333." ] test in firefox

the first result I can expect but what I can't expect is the second result. can anyone tell me why it get second result and tell me how to fix to get only the first one.

thanks~!

2
  • it's because capturing group, avoid that by non-capturing group add ?: ,/(?:\d{3}\.){3}\d{3}/; Commented Oct 12, 2015 at 13:03
  • 1
    Use non-capturing group: (?:\d{3}\.){3}\d{3}. Commented Oct 12, 2015 at 13:04

1 Answer 1

1

Capturing groups appear in String#match (without /g modifier) results as parts of the resulting array.

If the regular expression does not include the g flag, returns the same result as RegExp.exec().

And exec() help says:

If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.

To get rid of them, just replace capturing groups with non-capturing ones:

reg = /(?:\d{3}\.){3}\d{3}/;
//      ^^
var str8 = "111.222.333.444";
console.log(str8.match(reg));

Result: ["111.222.333.444", index: 0, input: "111.222.333.444"].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.