Consider the following Javascript code:
"use strict";
const myString = "hello this is my string lol";
const regexPattern = /(my|gah|nope)/;
const matchedString = myString.match(regexPattern);
console.log(matchedString);
The console output for this is as follows:
Array [ "my", "my" ]
According to what I’ve read of the documentation of JS regex (which includes a description of the pipe syntax used above) and the match method, this should only return an array of size 1, since only one instance of my exists in the string we are matching.
Why is the returned array 2 items long, and why does the matched item repeat within it?
The only way I was able to obtain the desired result (Array [ "my" ]) is if I added a g modifier to indicate a global search (i.e. /(my|gah|nope)/g). But I don’t understand why that would affect the result.
>Solution :
The behavior you’re seeing has nothing to do with alternatives, but is caused by the fact that match() (without the g flag) returns not only the first complete match, but also the value(s) of any capturing group(s) present in the expression (see MDN).
If you use an expression without capturing group you get the desired result.
const myString = "hello this is my string lol";
const regexPattern = /my|gah|nope/;
const matchedString = myString.match(regexPattern);
console.log(matchedString);
If you need grouping, but don’t want the capturing behavior, you can use a non-capturing group ((?:…)):
const myString = "hello this is my string lol";
const regexPattern = /(?:my|gah|nope)/;
const matchedString = myString.match(regexPattern);
console.log(matchedString);