Why does regex / [_-%] / break JavaScript?

The following JavaScript does not output anything (not even "false") and really stops the start of any other JavaScript on the page:

var pattern = new RegExp(/[_-%]/);
document.write(pattern.test("foo"));

What is this regular expression that it does? If any of the three characters (_, - or%) is deleted, everything works fine. And if the order of three characters changes at all, everything works fine.

+3
source share
4 answers

For ranges, a hyphen in the [] block is used. Therefore, the% to% value is invalid. You can avoid this:

var pattern = new RegExp(/[_\-%]/);

or go to the beginning:

var pattern = new RegExp(/[-_%]/);

or to the end:

var pattern = new RegExp(/[_%-]/);

Since the regular expression knows that a hyphen at the beginning (or end, thanks BrunoLM!) Means a literal hyphen, not a range.

+6
source

, , . , /[a-z]/ a z, /[_-%]/ () _ %. , JavaScript . .

+1

. JavaScript [_-%] , [A-Z]. , , , . (\-).

0

:

/[-_%]/

The - . \-

0

All Articles