Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

javascript - Why RegExp generates an error of "unexpected quantifier" on IE8?

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 like this ["utmccn", "utmcmd", /* ... */]. Well now there's not so much I can do, I'm at home with my friend the flu.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...