javascriptregexphotoshop-scriptecmascript-3

Regex parameters in a function


I'm trying to replace a fixed string in a regex wiht a parameter in a function. In my example, I'm looking for a string that starts with XF-98 (two letters, a hyphen, and a number)

var s = "XF-98 bananaas  ";

var regEx = (/XF\-\d+/mi); //NOT global
var result = s.match(regEx);
if (result != null) {
  alert(result);
  // do stuff
} else {
  alert("???" + s)
}

So far so good. But how do I convert it into this format where the prefix could be "XF-98", "XF-99" or "AB-1000"??

function check_string(mystring, prefix)
{
  var regEx = (/prefix\-\d+/mi); //NOT global
  var result = mystring.match(regEx);
  if (result != null) {
    alert(mystring);
    // do stuff
  }
}

Solution

  • You can use string concatenation or interpolation to build up your regex, and then use the RegExp constructor to create a RegExp instance:

    function check_string(mystring, prefix)
    {
      var regEx = new RegExp(`${prefix}-\\d+`, 'mi'); // NOT global
      var result = mystring.match(regEx);
      if (result != null)
      {
        alert(mystring);
        // do stuff
      }
    }
    

    A few pointers about calling the RegExp constructor with a string:

    EDIT:
    String templates were added to the es2015 specification. For older versions, you can use straightforward string concatenation, as @mplungjan mentioned in the comments:

    var regEx = new RegExp(prefix + '-\\d+', 'mi'); //NOT global