I am trying to cleanup some Javascript code using jshint. In a third-party script that is being used, jshint complains about unescaped javascript in this line:
var cleanString = deaccentedString.replace(/([|()[{.+*?^$\开发者_如何学JAVA\])/g,"\\$1");
I'd also like to understand what this regular expression does, but I don't see it. Can anyone tell me what this is for and how to write it in a cleaned up way?
Thank your for any hints.
It matches any of the following characters: |()[{.+*?^$\
and replaces it with its escaped counterpart (backslash plus that character).
While it is legal in many regex dialects to include an unescaped [
inside a character class, it can trigger an error in others, so try this:
var cleanString = deaccentedString.replace(/[|()\[{.+*?^$\\]/g,"\\$0");
(the unnecessary capturing group could be dropped, too.)
The regex is selecting "special" characters and stuffing a backslash in front. My guess is that it doesn't like the naked "[" in the character class, but that's just a guess. You might try:
var cleanString = deaccentedString.replace(/([|()\[{.+*?^$\\])/g,"\\$1");
Another option you have is to just not worry about what jshint says; it's just an advisory tool, after all, and if the code actually works properly in all browsers, well, the advice is clearly bad :-)
精彩评论