I have a Javascript error that have been reported to me and unfortunately I've no idea on how to reproduce it. IE8 Developer Tools reports the following error: Unexpected quantifier. The following row produces the error:
var g=RegExp(d+"=([^|]*)").exec(j); //output from closure-compiler
I guess I have to escape properly the pipe like that (\\|
) to fix the problem, but I don't know if I'm right because I don't know how to reproduce the error.
Any suggestions or solutions are welcome.
Thanks.
[UPDATE]
The values of d
are the keys of __utmz
cookie values which I'm trying to retrieve and they are listed in an array lik开发者_高级运维e this ["utmccn", "utmcmd", /* ... */]
. Well now there's not so much I can do, I'm at home with my friend the flu.
A "quantifier" is a regular expression operator like *
or +
. The variable "d" in the above code probably contains something that's being interpreted as "code" to the regular expression parser, and it's invalid. You're right that it needs to be appropriately escaped. It's a problem very similar to the problem of escaping text that's being included in HTML markup, but distinct because the syntax in question is completely different (that is, regular expression syntax vs. HTML syntax).
There are a lot of special characters in regular expression syntax, obviously, so it'll take a pretty gnarly regex to do that. Here's a possible way to do such a thing:
var quoted = unquoted.replace(/([*+.?|\\\[\]{}()])/g, '\\$1');
That might not get all of them; I'd look around for code that's more definitely tested than something a dope like me just made up :-)
Since that code you posted looks like it may come from some library, you may want to check the stack trace from the IE debugger to find out where the problem starts.
As a general rule you should always escape special characters inside character classes, you never know when you run into a regexp engine that will fail.
精彩评论