Take the 2-minute tour ×

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.

share|improve this question
add comment

5 Answers

up vote 143 down vote accepted

Pass in a regexp as the parameter:

js> "Hello awesome, world!".split(/[\s,]+/)

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]

... and if the pattern doesn't match:

>>> bits = "Hello awesome, world!".split(/foo/)
["Hello awesome, world!"]
>>> bits[bits.length - 1]
"Hello awesome, world!"
share|improve this answer
+1 for the character class and the + quantifier. –  Gumbo Mar 16 '09 at 11:33
What are you using for your js> console? –  Chris Mar 16 '09 at 11:34
rhino, Mozilla's implementation of JavaScript in Java: mozilla.org/rhino (... or "sudo apt-get install rhino"). –  Aaron Maenpaa Mar 16 '09 at 11:39
thanks. another question related to this what i need to do is get the last element of the splitted array. if there's no array it should return the string thx –  sol Mar 16 '09 at 17:33
Is there any way to avoid removing the separators when splitting with a regular expression? –  Anderson Green Jan 9 at 18:33
add comment

You can pass a regex into Javascript's split operator. For example:

"1,2 3".split(/,| /) 

Or, if you want to allow multiple separators together to act as one only:

"1, 2, , 3".split(/(?:,| )+/) 

(You have to use the non-capturing (?:) parens because otherwise it gets spliced back into the result. Or you can be smart like Aaron and use a character class.)

(Examples tested in Safari + FF)

share|improve this answer
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 Sep 21 '10 at 19:43
This method works better than character classes if you need to split on more than one character. Separate them by | as Jesse shows. –  chaiguy Jun 29 '12 at 21:36
I wonder if there's a way to avoid removing the separators when splitting a string with a regular expression: this example removes the separators, but I hope it's possible to split a string without removing them. –  Anderson Green Jan 9 at 18:32
@AndersonGreen It depends on exactly what you want; in this case, there are multiple separators, so do you want to keep them all? As a separate item? Joined to the previous item? Next item? It seems unclear to me. You might want to make a new question with some examples of what you're looking for. –  Jesse Rusak Jan 9 at 18:38
@JesseRusak I meant keeping all of the separators as separate items, so that a string could be tokenized using a list of separators. –  Anderson Green Jan 9 at 18:42
show 1 more comment

For those of you who want more customization in their splitting function, I wrote a recursive algorithm that splits a given string with a list of characters to split on. I wrote this before I saw the above post... I hope it helps some frustrated programmer...

splitString = function(string, splitters) {
    var list = [string];
    for(var i=0, len=splitters.length; i<len; i++) {
        traverseList(list, splitters[i], 0);
    return flatten(list);

traverseList = function(list, splitter, index) {
    if(list[index]) {
        if((list.constructor !== String) && (list[index].constructor === String))
            (list[index] != list[index].split(splitter)) ? list[index] = list[index].split(splitter) : null;
        (list[index].constructor === Array) ? traverseList(list[index], splitter, 0) : null;
        (list.constructor === Array) ? traverseList(list, splitter, index+1) : null;    

flatten = function(arr) {
    return arr.reduce(function(acc, val) {
        return acc.concat(val.constructor === Array ? flatten(val) : val);

var stringToSplit = "people and_other/things";
var splitList = [" ", "_", "/"];
splitString(stringToSplit, splitList);

Example above returns: ["people", "and", "other", "things"]

share|improve this answer
flatten function was taken from this website: Rosetta Code –  Stephen Sweriduk Aug 27 '12 at 15:26
add comment

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.

share|improve this answer
add comment

Tricky method:

var s = "dasdnk asd, (naks) :d skldma";
var a = s.replace('(',' ').replace(')',' ').replace(',',' ').split(' ');
console.log(a);//["dasdnk", "asd", "naks", ":d", "skldma"]
share|improve this answer
this is wrong because .replace() does not replaces all elements :/ –  2astalavista Jul 4 '13 at 14:47
you can change '(' for /(/g to replace all ( elements - g is the global flag for RegExp - so it search for all occurrences of ( not first one –  codename- Nov 20 '13 at 11:33
add comment

Your Answer

