views:

72

answers:

3

My codes is 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 just cannot get running with error message says: "RegExp.quote is not a function", am i missing something simple?

+6  A: 

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, "\\$1");
};

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.

Jørn Schou-Rode
Now SO generates answers to problems before they even exist!
RedFilter
That's a neat function, but it's important to be careful with things like that. It only works when you know that the string containing the pattern really does not intend to be interpreted with real regular expression metacharacters.
Pointy
@Pointy: I can only agree!
Jørn Schou-Rode
Oh, thanks! I searched out this question just a while ago, but i stop when i saw RegExp.quote in using, i thought RegExp.quote was a core function. But when i place the function in my scripts, it says: str.replace is not a function. Anyway, i can use the codes inside to escape my pattern.
Edward
@Relax: It would throw `str.replace is not a function` if you called it what some argument which is not a string. As long as the argument given is a string it should not throw.
Jørn Schou-Rode
I failed on using codes too, my pattern is from reg.exec: var pattern = anotherreg.exec(anotherstring); If it is not a string, how to convert it to?
Edward
i get it resolved with String(pattern), thanks anyway
Edward
A: 

Well, first of all you can define the regular expression with its own constant syntax:

var reg = /arrayname\[1\]/;

Inside the regular expression you quote things with backslash. Now, if you're starting from a string, you have to "protect" those backslashes inside the string constant. In that case, the pattern is being parsed twice: once when the string constant is gobbled by the Javascript parser, and then once by the RegExp constructor:

var pattern = "arrayname\\[1\\]";
var reg = new RegExp(pattern);

The backslashes are doubled so that the string "pattern" will look like the regular expression in my first example - one backslash before each bracket character.

Pointy
+1  A: 

If you're replacing literally, you don't need a regexp in the first place:

 str = str.split(search).join(replace)
stereofrog