In JavaScript, does an empty regex pattern have defined behavior?
var pattern = /(?:)/
开发者_JS百科
From my testing, it seems to match everything. Is this the defined behavior?
This doesn't directly answer the question, but here's what the spec has to say about the empty regular expression:
From 15.5.4.14 String.prototype.split (separator, limit)
The value of separator may be an empty String, an empty regular expression, or a regular expression that can match an empty String.
And from 7.8.5 Regular Expression Literals
NOTE Regular expression literals may not be empty; instead of representing an empty regular expression literal, the characters // start a single-line comment. To specify an empty regular expression, use:
/(?:)/
.
So given that it is an accepted value for the separator in .split()
, I would guess that it is the defined behavior as a way to split on every character.
"fjeij;als#%^&é.\n isoij\t;oi`1=+-]\r".split(/(?:)/);
["f", "j", "e", "i", "j", ";", "a", "l", "s", "#", "%", "^", "&", "é", ".", "
", " ", "i", "s", "o", "i", "j", " ", ";", "o", "i", "`", "1", "=", "+", "-", "]", "
"]
/(?:)/
matches "nothing", which matches everything. There is nothing in everything. Heh heh.
Yes, I would expect this.
精彩评论