4EverLive 4EverLive - 1 year ago 59
Javascript Question

Why does JavaScript string.split(/[ -_]+/) act as if quotes (' and ") are included in the [group]?

When using

/[ -_]+/
as parameter to string.split in JavaScript, it acts as if it was

"a'b".split(/[ -_]+/)
'a"b'.split(/[ -_]+/)


["a", "b"]

I only see this behavior with the exact regex:
[ -_]
i.e. space, hyphen, and underscore. If I remove any of these 3 characters it behaves (what appears to me to be) correctly, by not splitting on ' and "

Is this behavior correct?

Answer Source

- has special meaning inside of character classes. It denotes a range of characters. In this case the range is from space (ASCII 32) to underscore (ASCII 95). Because the ASCII codes for ' and " are 39 and 34 (respectively) they fall within that range.

Escape it if you want to split on a literal -;

"a'b".split(/[ \-_]+/)

Or make the hyphen the first character of the character class:

"a'b".split(/[- _]+/)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download