Edward Edward - 4 months ago 5x
Javascript Question

How to escape regular expression in javascript?

I have code like:

pattern = 'arrayname[1]'; // fetch from dom, make literal here just for example
reg = new RegExp(RegExp.quote(pattern), 'g');
mystring.replace(reg, 'arrayname[2]');

but it fails with an error message saying: "RegExp.quote is not a function".

Am I missing something simple?


This question got me searching on Google for a RegEx.quote function in JavaScript, which I was not aware of. It turns out that the function exists in only one place, namely in an answer by Gracenote here on StackOverflow. The function is defined like this:

RegExp.quote = function(str) {
    return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");

If you wish to use this function, you will need to include the above definition somewhere above the point where you use the function in your script.