Ask Ben: Splitting Strings In Javascript To Form New Variables

Posted December 19, 2008 at 2:53 PM

Tags: Javascript / DHTML, Ask Ben

I have a variable (string) with a value of: "foobar|http://www.myurl.com". From that, I want to make two new variables:

label: foobar
url: http://www.myurl.com

How do I split it?

Before we can answer this, we have to think about where variables live. Variables in any programming language always reside within some sort of a scope. Sometimes this scope has a label (as in "window") and sometimes this scope has no label (as in the local scope of a function). In order for us to be able to create new variables dynamically, we are going to need a reference to the scope in which they will be created.

In Javascript, if you do not specify a variables scope, it defaults to "window" - the global scope. That being said, creating a new variable, most of the time, is the exact same as creating a new key in an object. For example, when creating a global Javascript variable:

 Launch code in new window » Download code as text file »

  • var objData = {};

... is essentially the same as this:

 Launch code in new window » Download code as text file »

  • window[ "objData" ] = {};

Notice that our variable name, "objData", is nothing more than a key with in the "window" object (global scope).

Sound good? Now, let's look at a demo. In the following code, I am abstracting this idea out into a method, SetVariables(), that takes care of scoping the new variables for you:

 Launch code in new window » Download code as text file »

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  • <html>
  • <head>
  • <title>Splitting Strings Into Variables</title>
  •  
  • <script type="text/javascript">
  •  
  • // This will take a string that is formatted as a delimited
  • // list of values and store those values into the given
  • // variable names in the given container.
  • function SetVariables(
  • strList, // The list of values.
  • arrLabels, // The array of new variable names.
  • strDelimiter, // OPTIONAL - defaults to "|".
  • objContainer // OPTIONAL - defaults to "window".
  • ){
  •  
  • // Check to see if there is a defined container.
  • // If not then default the container to window.
  • // This is basically where any "unscoped" variable
  • // resides naturally.
  • if (!objContainer){
  • objContainer = window;
  • }
  •  
  • // Check to see if a delmiter was passed. If not,
  • // then define a default one.
  • if (!strDelimiter){
  • strDelimiter = "|";
  • }
  •  
  • // Now that we have our values defaults, we are
  • // going to split the string into an array using
  • // the given delimiter. Escape the delimiter in case
  • // it's a special regEx value.
  • var arrValues = strList.split(
  • new RegExp( ("\\" + strDelimiter), "gi" )
  • );
  •  
  • // Loop over the values and assign them to the
  • // labels passed in. Do this in order. In the loop
  • // conidition, make sure that we stay in bounds for
  • // both the value array and the variable name array.
  • for (
  • var i = 0 ;
  • (
  • (i < arrValues.length) &&
  • (i < arrLabels.length)
  • );
  • i++
  • ){
  •  
  • // Store the new value in the container
  • objContainer[ arrLabels[ i ] ] = arrValues[ i ];
  •  
  • }
  •  
  • // No need to pass back container as it is an object
  • // and will be passed by reference; but, let's just
  • // pass it back for good measure.
  • return( objContainer );
  • }
  •  
  • </script>
  • </head>
  • <body>
  •  
  • <h1>
  • Splitting Strings Into Variables
  • </h1>
  •  
  • <!--- Let's do some testing. --->
  • <script type="text/javascript">
  •  
  • // For the first test, we are going to use the default
  • // delimiter and the default container (window).
  • SetVariables(
  • "4|Naomi|Sexy",
  • [ "ID", "Name", "Description" ]
  • );
  •  
  • // Now, let's output those values.
  • document.write( "Window Test:<br />" );
  • document.write( "ID: " + ID + "<br />" );
  • document.write( "Name: " + Name + "<br />" );
  • document.write( "Description: " + Description + "<br />" );
  • document.write( "<br />" );
  •  
  •  
  • // Now, let's test this using a custom container. Since
  • // the container is the fourth argument, we HAVE to
  • // define the delimiter as well.
  • var objTest = {};
  •  
  • SetVariables(
  • "4|Naomi|Sexy",
  • [ "ID", "Name", "Description" ],
  • "|",
  • objTest
  • );
  •  
  • // Now, let's output those values.
  • document.write( "Custom Container Test:<br />" );
  • document.write( "ID: " + objTest.ID + "<br />" );
  • document.write( "Name: " + objTest.Name + "<br />" );
  • document.write( "Description: " + objTest.Description + "<br />" );
  • document.write( "<br />" );
  •  
  • </script>
  •  
  • </body>
  • </html>

In the demo, we are testing the SetVariables() first with the default behavior and then with a custom delimiter and container. When we run this code, we get:

Splitting Strings Into Variables

Window Test:
ID: 4
Name: Naomi
Description: Sexy

Custom Container Test:
ID: 4
Name: Naomi
Description: Sexy

Notice that the variables were dynamically set and then accessed successfully in both scope environments. Remember, the trick here is to remember that a variable cannot exist on its own - it can only exist as the element of given scope.

I hope that helps.

Download Code Snippet ZIP File

Post Comment  |  Ask Ben  |  Other Searches  |  Print Page



Learning ColdFusion 9 - ColdFusion 9 tutorials, samples, examples, demos

Reader Comments

Dec 19, 2008 at 4:12 PM // reply »
78 Comments

Normally I think your posts are right on Ben, sometimes a little verbose, but I respect that you're trying teach people instead of just answering their question. This one might be a case of going a little overboard.

Writing a function to split out a string with two keys (based on the pipe delimiter) just comes across as excessive, and not that helpful IMO to the OP.


Dec 19, 2008 at 4:22 PM // reply »
7,539 Comments

@Andy,

Totally valid point. There was actually a second-half to this conversation which talked about converting the above functionality into a jQuery plug-in. So, first, I wanted to discuss the abstraction of the idea (above) and then probably follow it up with a post on the jQuery plug-in.

But yeah, this is a bit wordy :)


Dec 19, 2008 at 5:43 PM // reply »
26 Comments

var urlData = "foobar|http://www.myurl.com";
var urlStruct = {"label": urlData.split("|")[0], "url": urlData.split("|")[1]};


Dec 19, 2008 at 9:12 PM // reply »
78 Comments

If you assign the split to a variable first, you'll save yourself a small amount of processing, avoiding the split twice:

var urlData = "foobar|http://www.myurl.com".split("|");
var urlStruct = {"label": urlData[0], "url": urlData[1]};


Post Comment  |  Ask Ben

Recent Blog Comments
Mar 18, 2010 at 1:18 PM
Finally Finished Ayn Rand's Atlas Shrugged Audio Book
@joaopft, Not disputing what you say - but... If I understand you correctly, you are saying that Positivism is based on sense experience (what I experience is what is), but Quantum theory states tha ... read »
Mar 18, 2010 at 11:48 AM
Duplicate() Much Faster Than ColdFusion Query-of-Queries
I am working on a massive xml parsing, qofq app to create 2 seperate xml files. I just don't understand the concept/purpose of duplicate function, are you duplicating the data or the row, into a new ... read »
Mar 18, 2010 at 11:22 AM
Exploring ColdFusion Component Runtime Class Properties And Serialization
@Zarko, Ha ha, you know ColdFusion is my first love ;) ... read »
Mar 18, 2010 at 11:15 AM
Exploring ColdFusion Component Runtime Class Properties And Serialization
Hi Ben, nice to have you back! I already gave up on you, thinking you'll write about jQuery and iPhone for the rest our our lives! :) ... read »
Mar 18, 2010 at 10:36 AM
Ask Ben: Javascript Replace And Multiple Lines / Line Breaks
@Ben Nadel, Hey Ben, thanks for you're response. It works!! However.. if you could please kindly look at http://edeals.zzl.org/divchange2.php where I am trying it out you will see that with the " ... read »
Mar 18, 2010 at 9:56 AM
SQL COUNT( NULLIF( .. ) ) Is Totally Awesome
This works too. I learned this trick a long time ago and it's really powerful for flags. SELECT g.hair , COUNT(*) AS girl_count , sum(did_date) AS did_date_count , sum(abs(did_date - 1)) AS did_ ... read »
Mar 18, 2010 at 9:16 AM
Using A SQL JOIN In A SQL DELETE Statement (Thanks Pinal Dave!)
Forget the last part of that. Wasn't thinking straight and hadn't done it exactly that way myself. It'll work if you're doing an 'In' but if you're doing a 'Not In' as above it'll do each check acr ... read »
Mar 18, 2010 at 9:16 AM
Ask Ben: Blocking WSDL Access In A ColdFusion Application
Ben, Robert great stuff that I can use. Thanks. ... read »