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,246 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,246 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 »
40 Comments

Walk like an Egyptian.


Apr 7, 2011 at 10:28 PM // reply »
11,246 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
May 24, 2013 at 9:11 AM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Brandon, Hi, No, I haven't been able to do that. I have just kept it as it is. ... read »
May 23, 2013 at 9:52 PM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Muhmmadibn Did you figure out a solution to launching PDFs? I am running into the same issues myself. There is no way to close the PDF or go back once you launch it. Thanks in advance! ... read »
May 23, 2013 at 6:06 PM
The Girl Who Broke My Heart, And Made Me A Better Person
Good day,ladies and gentle men, my name is Dr AMADI the great spell caster in Africa, i have help so many people for different kind of problems,who say there is no solution to problems on earth, that ... read »
May 23, 2013 at 4:26 PM
ColdFusion QueryAppend( qOne, qTwo )
@Heather, Glad people are still getting value out of this! ... read »
May 23, 2013 at 3:49 PM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, I meant the code at the bottom (not the video). I did try to experiment with an intermediary variable, like: value = users.id[ i ]; arrayContains( userIDs, value ); ... but t ... read »
May 23, 2013 at 11:06 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Are you talking about As Number: YES As String: YES As Java: YES? If so, that's with 3 different ways of referencing the constant 1, not users.id[1]. Query object references(*) are what seem ... read »
May 23, 2013 at 9:55 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Dan, According to the CF Admin, I'm running Java "1.6.0_45". As far as the DB column, in the database it's an INT. I'll see if I can dig into what CF sees it as. @WebManWalking, But h ... read »
May 23, 2013 at 9:49 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, I think the problem is that we're used to loose typing in ColdFusion, like JavaScript. If a value is a number but it's needed in an expression to be a string, noooo problem. I've encountered ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools