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 »
168 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 »
10,640 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 »
10,640 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 »
168 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 »
33 Comments

Walk like an Egyptian.


Apr 7, 2011 at 10:28 PM // reply »
10,640 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
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 12, 2012 at 3:37 AM
Learning ColdFusion 8: CFImage Part III - Watermarks And Transparency
Hi Ben, Just to ask currently it is placed bottom right corner, if i need to replace the same rendered image on the bottom left side or in the bottom center, how that can be calculated. bottom ce ... read »
Feb 11, 2012 at 9:29 PM
Use jQuery's SlideDown() With Fixed-Width Elements To Prevent Jumping
I can't say how glad I am that I found your post. Thank you very much. ... read »
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »