The Frontier Group - Blog

JavaScript and String Building

November 6th, 2008, by tony

In most languages there is a means of building strings and printing out messages. Many will find the printf command all too familiar. In the JavaScript space however things have been a little slow to develop.

We have our strings and to build them up we merely start adding them together but as our code gets more elaborate this gets harder and harder. The biggest problem is usually trying to figure out how to escape quotes and inverted commas as we swap back and forth between plain strings and JavaScript variables.

I’ve often thought there must be a better way and working with the Dojo toolkit there is. It can be found in the method “dojo.string.substitute”. This mirrors the idea used in other languages of passing the method a template string and an object of values to substitute in. Whilst Dojo allows for numerous ways of passing the data such as arrays and functions the one that interests me the most is a standard JavaScript object which is effectively a hash map of name and value pairs.

Here’s a simplified version of the Dojo function that only uses objects for the value map.

var tfg = {
  string:{
    substitute: function(/*String*/ template, /*Object*/ valueMap){
      return template.replace(/\$\{([^\s\:\}]+)(?:\:([^\s\:\}]+))?\}/g, function(match, key){
            return (valueMap[key])?valueMap[key]:"";
        });
    }
  }
}

The old way of doing things might look like this:

var data = {name:"bob", occupation: "builder"};
var string = "His name is "+data.name+" and is occupation is "+data.occupation+".";

Here we merely add the different parts of the string and string values together. Simple enough in a string this size but as it grows and we start working with HTML syntax things get more complicated.

Using the substitute way:

var data = {name:"bob", occupation: "builder"};
var template = "His name is ${name} and is occupation is ${occupation}.";
var str = tfg.string.substitute(template, data);

Here anything surrounded by the format “${something}” is replaced with the value found in “data.something”.

A major advantage of this approach is when we start looking at fetching JSON data sets from a remote server via Ajax. We almost always have to process the return values into something to display and if it is looping through a list of objects we can now define the template once and repeatedly create a string with our substitute method. Here’s a simple idea using JQuery for the loop.

var result = [{name:"a",company:"1"},{name:"b",company:"2"}];
var template = "<tr><td>${name}</td><td>${company}</td></tr>";
var rows = $.map(result, function(index, item){
  return tfg.string.substitute(template, item);
})
var tableBodyString = rows.join("\n");

Here we looped through the items substituting each new set of values and pushing the result into an array. At the end we merge the array into a single string with “join” and have the body of a HTML table ready to be used in the page.

This approach is fast, easier to read and much cleaner to implement when looping through data.

We are a web development company and this is our blog. We specialize in building web applications with the Ruby on Rails framework. You can read more about our Ruby on Rails development or contact us.

One Response to “JavaScript and String Building”

  1. mlambie says:

    This really reminds me of the in-place variable substation that you can do with languages like PHP and Ruby. It makes the string so much more readable than a bunch of concatenations.

Leave a Reply


Follow Us

Stay in the Loop

  • Enter your email address to subscribe to our mailing list. You'll get updates about our products, specials and bonus offers, and general behind the scenes news from our team.

Twitter

Newsletters

Alexa Rank

Testimonial

The boys at The Frontier Group are amazing! For such a relaxed and personable organisation, they have phenomenal technical ability and a rampant professionalism. They have customisable solutions for all of my IT needs and they always deliver, on time and beyond expectation.

They fix problems other service providers can't and they helped me get a critical section of my web site up and running 10 minutes after I emailed the request!

Alex Hyndman, Nexus Car Share.

Featured Project

Case Study - Caudo Group - www.caudo.com.au

Website

www.caudo.com.au

Caudo Machinery

Caudo Group engaged our services to redesign their outdated website. We sent our photographer on-site to capture the essence of their business and turned it into a stunning web design.