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
}
}
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:
\
) is an escape character for both strings and regexes, so if you want it in your regex (e.g., to escape the d+
), you'll need to double it.-
character. This isn't a special character in a regex (at least, not when outside of a range), and doesn't need escaping./
characters that are used to denote a regexp literal.mi
) have their own argument.prefix
argument comes from user input, you need to be very careful with it, and probably sanitize/validate it first. Otherwise, your code might be vulnerable to ReDoS.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