javascript string.split on multiple characters

Today I was asked how to split an array, in javascript, on multiple characters, for example, a space or comma. I didn’t know, so I decided to think on it for a bit, then do some research. The three options that came to mind were, in the order I thought of, and oddly enough, worst to best.

The first was to simply split on a single character, then do it again, but that would require sending an array of strings into a splint function, each. For example, splittin “hello world,twice” on a space and comma, first being split on space, would produce an array of two strings, and you would need to loop through that, calling split on a comma. So an array that’s split into 8 items, would then need 8 more split calls, then the arrays would need to be merged into one single array, and that’s not ideal, but it works.

var string = "this is a string,and I have a comma";
var array = string.split(" ");
var finishedArray = [];
for (var i = 0, il = array.length; i < il; i++) {
  var temp = array[i].split(",");
  for (var j, jl = temp.length; i < jl; j++) {

It works, but, no… it’s not good. Am I missing something with this?

Option number two, and my personal favorite, simply because it’s not so obvious, is to, taking the last example of space and comma, turn all comma’s into spaces using replace, then calling split on just space, something like this.

var string = "this is a string,and I have a comma";
var array = string.replace(",", " ").split(" ");

The final option, and the right option, is to simply just split on a regular expression.

var string = "this is a string,and I have a comma";
var array = string.split(/[\s,]+/);

The contents between the / / means this is a “regular expression”, and the [] means any one of the desired character, and best of all, the \s, means any space character, including tabs and newline.

I feel the bottom two are both perfectly acceptable.


One Response to “javascript string.split on multiple characters”

  1. Thanks !!!!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: