I thought it would split at comas with any number of spaces before or after.
That is correct. It will even match commas with no spaces before and after.
The /
before and after is just a syntax that some regex parsers uses as a delimiter for the regex expression.
In Javascript you should use split('string')
(apostrophes) for splitting on strings or characters, and split(/regexp/)
(slashes) for splitting on regex expressions.
The double backslash (\\
) is used to escape special characters in strings so that e.g. '\n'
is interpreted as a single line-feed character while '\\n'
is interpreted as a backslash and an "n" ('\n'
).
When using the regex delimiters /
on your expression, you don't have to escape special characters as the parser knows it's a regex.
split(/\s*,\s*/) // No escaping needed with backslash delimiters.