snippetjavascriptCritical
How do I split a string with multiple separators in JavaScript?
Viewed 0 times
withhowseparatorssplitmultiplestringjavascript
Problem
How do I split a string with multiple separators in JavaScript?
I'm trying to split on both commas and spaces, but AFAIK JavaScript's
I'm trying to split on both commas and spaces, but AFAIK JavaScript's
split() function only supports one separator.Solution
Pass in a regexp as the parameter:
Edited to add:
You can get the last element by selecting the length of the array minus 1:
... and if the pattern doesn't match:
js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!Edited to add:
You can get the last element by selecting the length of the array minus 1:
>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]
>>> bit = bits[bits.length - 1]
"world!"... and if the pattern doesn't match:
>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"Code Snippets
js> "Hello awesome, world!".split(/[\s,]+/)
Hello,awesome,world!>>> bits = "Hello awesome, world!".split(/[\s,]+/)
["Hello", "awesome", "world!"]
>>> bit = bits[bits.length - 1]
"world!">>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"Context
Stack Overflow Q#650022, score: 1020
Revisions (0)
No revisions yet.