Ask Ben: Splitting Strings In Javascript To Form New Variables

Posted December 19, 2008 at 2:53 PM by Ben Nadel

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:

  • var objData = {};

... is essentially the same as this:

  • 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:

  • <!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.



Reader Comments

Dec 19, 2008 at 4:12 PM // reply »
92 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 »
11,238 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 »
92 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 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 20, 2013 at 11:45 AM
Using jQuery's Animate() Step Callback Function To Create Custom Animations
This is really useful. I found out that you don't actually have to use a dummy css property (surprisingly). To animate a property in a linear-gradient for instance I did this this.css('someLinearGra ... read »
May 20, 2013 at 10:51 AM
Using A Dynamic Column Name With ValueList() In ColdFusion
@Josh, Oh snap! You're totally right! I'm not sure I've ever tried that. I did know that you can call a number of other array-methods on ColdFusion query columns: http://www.bennadel.com/blog/167 ... read »
May 20, 2013 at 10:45 AM
Using A Dynamic Column Name With ValueList() In ColdFusion
@Ben - I believe you can achieve the same functionality with ColdFusion's built in ArrayToList() function. ArrayToList( users[ "id" ] ); ... read »
May 20, 2013 at 10:21 AM
My Experience With AngularJS - The Super-heroic JavaScript MVW Framework
Is there any error logging and handling framework in angularjs, if not then in what way I can do this. ... read »
May 19, 2013 at 2:31 PM
My Experience With AngularJS - The Super-heroic JavaScript MVW Framework
It's funny really just how well that image describes the way I would imagine most people that go with angular for some project is. I have had a similar roller-coaster ride with it as well, but not qu ... read »
May 17, 2013 at 7:42 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
Ben - thanks so much for posting these Angular articles and findings, they've been a huge help towards learning one of the more 'complex' JavaScript frameworks out there (IMO). I have been using Angu ... read »
May 16, 2013 at 5:01 PM
UPDATE: Parsing CSV Data Files In ColdFusion With csvToArray()
Your code was the closest thing I've found to obtaining some direction for converting ISO fields to values that CF can translate properly. Thank you for posting! ... read »
May 15, 2013 at 6:07 PM
Making SOAP Web Service Requests With ColdFusion And CFHTTP
Ben, you once again saved my bacon at work. Thank you, thank you, thank you! ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools