Search code examples
javascriptregexvariablesmatchimplicit

javascript match implicit variable


I'm unable to determine if there is an implicit variable for match results in javascript.

The resulting code which I'm looking for is this:

if(line.match(/foo{bar}/)) {
  console.log(bar_variable)
}

the referenced ^ bar_variable should contain the match group result. Is there anything like this?


Solution

  • No, there is not. String.match() returns:

    An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

    So you could do something like:

    if (bar_variable = line.match(/foo{bar}/)) {
      console.log(bar_variable)
    }
    

    To avoid a global symbol you could do something like this, but it does make it a bit uglier:

    {
      let bar_variable;
      if (bar_variable = line.match(/foo{bar}/)) {
        console.log(bar_variable);
      }
    }
    

    As far as I know you can't do if (let x = ...) but I could be wrong.