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
demo
I don’t have a clue what is going on, anything that enlightens me is welcome
The second
foxisn’t actually a match. It is a captured group. By default, parentheses make a capturing group. So in your example,foxis what is matched inside the parentheses, while#foxis the whole match.To write the regex without the capturing group, do this:
You can also specify a non-capturing group with this syntax:
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.