views:

4583

answers:

3

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
+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
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
+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
+1 for the character class and the `+` quantifier.
Gumbo
What are you using for your js> console?
Chris
rhino, Mozilla's implementation of JavaScript in Java: http://www.mozilla.org/rhino/ (... or "sudo apt-get install rhino").
Aaron Maenpaa
thanks. another question related to thiswhat i need to do is get the last element of the splitted array. if there's no array it should return the stringthx