How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and spaces but, AFAIK, js's split function only supports one separator.
A:
Perhaps you should do some sort of string replace to turn one separator into the other separator so you then only have one separator to deal with in your split.
TheTXI
2009-03-16 11:28:49
+3
A:
You can pass a regex into Javascript's split operator. For example:
"1,2 3".split(/,| /)
["1", "2", "3"]
Or, if you want to allow multiple separators together to act as one only:
"1, 2, , 3".split(/(?:,| )+/)
["1", "2", "3"]
(You have to use the non-capturing (?:) parens because otherwise it gets spliced back into the result. Or you can be smart like zacherates and use a character class.)
(Examples tested in Safari + FF)
Jesse Rusak
2009-03-16 11:29:36
If you need multiple characters to act as one, as in, say "one;#two;#new jersey", you can simply pass the string ";#" to the split function. "one;#two;#new jersey".split(";#")[2] === "new jersey"
Oskar Austegard
2010-09-21 19:43:26
+13
A:
Pass in a regexp as the parameter:
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!"
Aaron Maenpaa
2009-03-16 11:30:45
rhino, Mozilla's implementation of JavaScript in Java: http://www.mozilla.org/rhino/ (... or "sudo apt-get install rhino").
Aaron Maenpaa
2009-03-16 11:39:37