Short answer:
function escapeRegEx(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var expression = new RegExp('\\\\"mediaType\\\\":\\\\"' + escapeRegEx(variable) + '\\\\"');
// or, using a template literal:
var expression = new RegExp(`\\\\"mediaType\\\\":\\\\"${escapeRegEx(variable)}\\\\"`);
Long answer:
Besides being used for meta characters, backslash in regular expressions can be used to escape characters that would otherwise have meaning (like *
, $
, parentheses, and \
). So the way to match a backslash in a regular expression is to add another one as an escape character: \\
.
Taking that into account, the regular expression you want to end up with is \\"mediaType\\":\\"img\\"
, and if you were using a regular expression literal that would be it. Unfortunately it gets a little more involved because you need to create an expression dynamically, you need to provide the expression as a string, which also needs the backslashes escaped. That adds a second layer of escaping, so you need to double up each of the \
characters again, and you end up with new RegExp('\\\\"mediaType\\\\":\\\\"img\\\\"')
.
Another complication is that you want the contents of variable
to be matched literally, not interpreted as a regular expression. Unfortunately, there's no built-in way to automatically escape regular expressions in JavaScript, so you'll need to use one of the solutions in Is there a RegExp.escape function in Javascript?. I used a slightly modified version of the accepted answer that defines it as a standalone function instead of adding it to the RegExp
object. The exact solution doesn't matter, as long as you escape the dynamic part.