javascriptarraysregexcontentplaceholder

How to "place-hold" regex matches in array using javascript


If I have a multiple match regex like:

var matches = string.match(/\s*(match1)?\s*(match2)?(match3)?\s*/i);

and if my string that I am testing is like this:

var string = "match1 match3";

is there a way to output this array values:

matches[1] = "match1";
matches[2] = "";
matches[3] = "match3";

Notice: what I would like is for the regex to match the entire thing but "place-hold" in the array the matches it does not find.

Hope this makes sense. Thanks for the help!


Solution

  • There already is a "placeholder". Unmatched groups pop an array index matching the group number with an undefined value. e.g.

    var someString = "match2";
    var matches = someString.match(/\s*(match1)?\s*(match2)?(match3)?\s*/i);
    

    matches now has

    ["match2", undefined, "match2", undefined]

    Element 0 is the complete regex match and elements 1-3 are the individual groups

    So you can do for example...

    // check if group1
    if (typeof matches[1] != 'undefined')