0

I have this code that when I remove the global flag, it is matching an extra fox:

var str = "...brown #fox jumped...";

var arr1 = str.match(/#([^\s]+)/g); //["#fox"]
var arr2 = str.match(/#([^\s]+)/); //["#fox", "fox"]

console.log(arr1.join(", ")); //#fox
console.log(arr2.join(", ")); //#fox, fox

(source of code)

demo

I don't have a clue what is going on, anything that enlightens me is welcome

Community
  • 1
  • 1
ajax333221
  • 11,436
  • 16
  • 61
  • 95

2 Answers2

4

The first item is the string that matches the whole regular expression. All the next items are correspondent values of matches within braces (...)

PS: [^\s] can be written as [\S]

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • 2
    Probably worth mentioning that `match` behaves differently when the `g` flag is (not) used: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match#Description – Andrew Whitaker May 17 '12 at 02:15
  • @Andrew Whitaker: It would worth if it was explanation there. I cannot find any official explanation, but from my perspective it is obvious – zerkms May 17 '12 at 02:16
  • I am not sure if this entirely explain why this happen (or at least I am missing it), PS: I +1'd because your PS – ajax333221 May 17 '12 at 02:29
2

The second fox isn't actually a match. It is a captured group. By default, parentheses make a capturing group. So in your example, fox is what is matched inside the parentheses, while #fox is the whole match.

To write the regex without the capturing group, do this:

#\S+

You can also specify a non-capturing group with this syntax:

#(?:\S+)

The global flag prevented the capturing group from capturing, because the String match function doesn't get captured groups if the global flag is set. The Regex exec function will get the capturing groups, as described in this question and answer.

Community
  • 1
  • 1
Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
  • but why the group only was added without the global flag, I can't possible see how something that do less checks return more than one with global falg – ajax333221 May 17 '12 at 03:00