Why does the regular expression /[_-%]/ break JavaScript?
The following JavaScript outputs nothing (not even "false"), and indeed stops any other JavaScript on the page from 开发者_开发问答running:
var pattern = new RegExp(/[_-%]/);
document.write(pattern.test("foo"));
What is it about this regular expression that does this? If any one of the three characters (_, -, or %) is removed, everything works normally. And if the order of the three characters is changed at all, everything works normally.
A hyphen in a [ ] block is used for ranges. So _ to % is invalid. You can escape it:
var pattern = new RegExp(/[_\-%]/);
or move to the start:
var pattern = new RegExp(/[-_%]/);
or to the end:
var pattern = new RegExp(/[_%-]/);
Since regex knows that a hyphen at the start (or end, thanks BrunoLM!) means a literal hyphen and not a range.
It's because in the interpreter thinks it's dealing with a range. Just like /[a-z]/
will match any character between a
and z
, /[_-%]/
will (try to) match any character between _
and %
. This doesn't make sense, so JavaScript stops. Putting the hyphen as the first or last character will fix the issue.
It's the dash in the middle. JavaScript treats [_-%]
as a character class range, similar to [A-Z]
. I'm guessing the browser you're using simply doesn't handle this case very well. I suggest moving the hyphen to the front, or escaping it with a backslash (\-
).
Use the following instead:
/[-_%]/
The - would have been interpreted to be a range. You can also use \-
精彩评论