In Perl regular expressions, you can surround a subexpression with \Q
and \E
to indicate that you want that subexpression to be matched as a literal string even if there are metacharacters in there. You also have the quotemeta
function that inserts exactly the right number of backslashes in a string so that if you subsequently interpolate that string into a regular expression, it will be matched literally, no matter what its contents were.
Does Javascript (as deployed in major browsers) have any built in equivalent? I can write my own just fine, but I would like to know if I don't have to bother.
There is no such built-in feature.
Rather than implementing your own, I advise you look into the multitude of regex escape functions available on the internet.
That page proposes the following solution (by Colin Snover):
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
or advises to use the XRegExp library.
Quotemeta isn't implemented natively as far as I know, but I've used this a few months ago for just this:
function quotemeta (str) {
// http://kevin.vanzonneveld.net
// + original by: Paulo Freitas
// * example 1: quotemeta(". + * ? ^ ( $ )");
// * returns 1: '\. \+ \* \? \^ \( \$ \)'
return (str + '').replace(/([\.\\\+\*\?\[\^\]\$\(\)])/g, '\\$1');
}
From http://phpjs.org/functions/quotemeta:496
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With