Ask Ben: Converting Javascript Lists To Arrays

Posted July 18, 2006 at 10:08 AM by Ben Nadel

Tags: Javascript / DHTML, Ask Ben

Is there a way in Javascript to convert a list to an array like ColdFusion's ListToArray() method?

You can convert a list to an array using the String::split() method. The Javascript split() method is quite similar to the ColdFusion ListToArray() method. Both take a string list and split the list based on a given delimiter. As with all things Javascript, there is a simple version and an advanced version.

Let's start off creating a list in javascript:

  • // Create a pipe-delimited list (|) of movies.
  • var strMovieList = "Over 40 vol.10|Mega Butt vol.3|Barely Legal vol.18";

The simple version uses a constant string as the list delimiter:

  • var arrMovies = strMovieList.split( "|" );

In this case, we are using the pipe character "|" as our delimiter. This call will return an array with three values:

  • arrMovies[ 0 ] == "Over 40 vol.10";
  • arrMovies[ 1 ] == "Mega Butt vol.3";
  • arrMovies[ 2 ] == "Barely Legal vol.18";

The difference here between Javascript and ColdFusion is that in Javascript, you cannot pass multiple delimiters into split(). If you attempted to use the pipe and the comma as a delimiter and passed in:

  • var arrMovies = strMovieList.split( "|," );

... you will only get an array with one value, the original string, since the substring "|," could not be found in the original list.

That's where the advanced version comes in. And yes, you guessed it: it involves are good friend, the Regular Expression. Instead of passing a static string into split(), you can pass in a regular expression (RegExp) that will be used to split the list. Let's say we didn't just want to break out the individual movies. Let's say we wanted to break out the individual words into an array. To do so, we would want to split on both the pipe "|" AND the space " " characters:

  • var arrMovies = strMovieList.split( new RegExp( "[| ]{1}", "g" ) );

This will give us an array of all the words in the original list.

Now, if you have been paying attention to previous posts, you will remember that the RegExp() constructor takes in a second argument, the flags ("g", "i"). In this case, we are sending the flag "g" for "global" but it is not really required. I do it out of habit, but splitting a string is global no matter what (as far as I know). You can and should use the case insensitive flag "i" if it is required when splitting.



Reader Comments

Jun 23, 2007 at 8:14 PM // reply »
172 Comments

There are a number of gotcha's when using a regex to split a string in JavaScript, since all current, major browsers have some related bugs. In particular, IE doesn't include empty values in the returned array when using a regex as the delimiter (though it does when using a string as delimiter).

See this page for a fix: http://blog.stevenlevithan.com/javascript/cross-browser-split/


Jun 25, 2007 at 7:17 AM // reply »
11,314 Comments

@Steve,

That function you wrote looks pretty cool.


mel
Jul 23, 2007 at 2:05 PM // reply »
1 Comments

Great tip, helped solve my javascript problem I was running into.


Nov 5, 2008 at 12:55 AM // reply »
1 Comments

Great document. Using Javascript, is it possible to split on multiple delimiters AND include the delimiters in the split array response?

e.g.

"a+b-c".split(new RegExp("[+-]", "g"))

... returns ...

a
b
c

How do I get it to return ...

a
+
b
-
c

Someone, somewhere on some forum stated that this could be done by wrapping the delimiters in the RegExp expression in parenthesis but that didn't work for me.


Nov 5, 2008 at 8:33 AM // reply »
11,314 Comments

@Rohit,

Did you try passing the empty string to the split method:

"string".split( "" )

That might work?


Nov 5, 2008 at 4:12 PM // reply »
172 Comments

@Rohit, using capturing parentheses in your split pattern probably didn't work for you since you're using Internet Explorer, which doesn't follow the JavaScript split specification on that point. It will work if you first run the following script, which fixes String.prototype.split cross-browser:

http://blog.stevenlevithan.com/archives/cross-browser-split


Jan 3, 2010 at 8:31 AM // reply »
1 Comments

Nice movie selection(?) Haha... the function works great. Thanks a million Ben.


Feb 4, 2010 at 5:37 AM // reply »
1 Comments

Haha, the movie list rocks!


Apr 7, 2011 at 5:27 PM // reply »
43 Comments

Walk like an Egyptian.


Apr 7, 2011 at 10:28 PM // reply »
11,314 Comments

@Chad, @Virgil,

Ha ha, glad it was amusing.

@Phillip,

That, my friend, is random!


Jul 25, 2011 at 1:21 PM // reply »
1 Comments

Lol @ Over 40 Vol. 10

Nice one.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Jun 20, 2013 at 3:15 AM
A Billion Wicked Thoughts By Ogi Ogas And Sai Gaddam
nice post i love it thanks 4 u :) ... read »
seb
Jun 20, 2013 at 2:32 AM
Working With Inherited Collections In AngularJS
@mike, @ben, The best article about scope and prototypal prototypical inheritance in angularjs is http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical- ... read »
Jun 20, 2013 at 2:17 AM
ColdFusion NumberFormat() Exploration
Nice read thanks Ben, Is there a way to mask a negative number? Long story short in the finance sector when you go 'short' on a stock you want the price to fall this is a good thing because you are ... read »
Jun 20, 2013 at 1:09 AM
The Beauty Of The jQuery Each() Method
my html code : <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="nss.js"> ... read »
Jun 19, 2013 at 11:31 PM
Directive Link, $observe, And $watch Functions Execute Inside An AngularJS Context
@Ben, bunch to learn indeed, but thats fun part : ) ... read »
Jun 19, 2013 at 10:41 PM
Referencing ColdFusion Query Columns In A Loop Using Both Array And Dot Notation
Burdock-roots Are you going fat day by day? You need to be good for your family and make some money too. So we bring for you a best product that helps you to be more energetic every day. You will b ... read »
Jun 19, 2013 at 9:52 PM
Working With Inherited Collections In AngularJS
I recognize the applicability of your solution, and how easy it makes to share data across multiple views or even "submodules" of rather simple application. But it seems to me that it creat ... read »
Jun 19, 2013 at 9:38 PM
Directive Link, $observe, And $watch Functions Execute Inside An AngularJS Context
@Alesei, Glad you like it. Even after working with AngularJS for months, I still get a bunch of unexpected, "$digest is already in progress". So hard to debug sometimes! ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools