How to properly escape characters in regexp
Solution 1:
\Q...\E
doesn't work in JavaScript (at least, they don't escape anything...) as you can see:
var s = "*";
print(s.search(/\Q*\E/));
print(s.search(/\*/));
produces:
-1
0
as you can see on Ideone.
The following chars need to be escaped:
(
)
[
{
*
+
.
$
^
\
|
?
So, something like this would do:
function quote(regex) {
return regex.replace(/([()[{*+.$^\\|?])/g, '\\$1');
}
No, ]
and }
don't need to be escaped: they have no special meaning, only their opening counter parts.
Note that when using a literal regex, /.../
, you also need to escape the /
char. However, /
is not a regex meta character: when using it in a RegExp
object, it doesn't need an escape.
Solution 2:
I'm just dipping my feet in Javascript, but is there a reason you need to use the regex engine at all? How about
var sNeedle = '*Stars!*';
var sMySTR = 'The contents of this string have no importance';
if ( sMySTR.indexOf(sNeedle) > -1 ) {
//found it
}
Solution 3:
I performed a quick Google search to see what's out there and it appears that you've got a few options for escaping regular expression characters. According to one page, you can define & run a function like below to escape problematic characters:
RegExp.escape = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
Alternatively, you can try and use a separate library such as XRegExp, which already handles nuances you're trying to re-solve.