Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does a Javascript regular expression with alternatives generate an array of size 2 when there is only 1 match?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading