I am trying to cleanup some Javascript code using jshint. In a third-party script that is being used, jshint plains about unescaped javascript in this line:
var cleanString = deaccentedString.replace(/([|()[{.+*?^$\\])/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.
I am trying to cleanup some Javascript code using jshint. In a third-party script that is being used, jshint plains about unescaped javascript in this line:
var cleanString = deaccentedString.replace(/([|()[{.+*?^$\\])/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.
Share Improve this question edited Mar 4, 2013 at 16:45 James Allardice 166k22 gold badges334 silver badges315 bronze badges asked Jun 6, 2011 at 13:43 MutzMutz 451 silver badge3 bronze badges 1- That's a bug in JSHint. The regular expression looks like junk out of context. – Raynos Commented Jun 6, 2011 at 13:49
2 Answers
Reset to default 5It 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 :-)