Using Prototype’s New String Functions

3 am on August 31st, 2006

After years of extensive research and study, I’ve come to a profound conclusion — working with strings sucks. It’s even more difficult when you’re doing it in JavaScript. Lucky for us, the Prototype JavaScript framework provides several shiny new String object functions to make our lives easier. Sounds like a perfect chance to be lazy — let’s get to work!

Note: I’m working with the new String methods in Prototype 1.5.

Let’s create a simple string we can run some manipulations on:

var string = 'Laziness always pays off now.';

String.gsub

The gsub method is similar to the native replace method, but it’s even more powerful. It accepts 2 arguments, the first one being the pattern to search for. This can be a simple string or a regular expression. The second argument is what to replace the matched pattern with.

Let’s start with something easy. I’m tired of spaces, so let’s replace them with underscores.

string.gsub(' ', '_');    // Returns "Laziness_always_pays_off_now."

Not very exciting, and we could have accomplished the same thing with string.replace(/\s/g, ‘_’). Where gsub really starts to shine is when you realize that the second argument can be a function. This function will run on each match found in the string. The function receives one argument, an array of matches against the pattern. You then return a manipulated version of the string. Sound confusing? Follow the bouncing code:

string.gsub(/\s\w/, function(match){ return match[0].toUpperCase(); });
 // Returns "Laziness Always Pays Off Now."

Each match is passed to the function, which can then manipulate the match and return the version to replace. We needed to reference the match as match[0] because the matches of a regular expression are returned as an array. Index 0 is the entire match, and each numeric index after that corresponds to a parenthesis group in the regular expression. If we had used parenthesis in the regular expression, we could have accessed other elements of the match array:

string.gsub(/(s|f)(\s)/, function(match){ return match[1].toUpperCase() + '-' + match[2]; });
// Returns "LazinesS- alwayS- payS- ofF- now."

String.sub

String.sub is almost identical to String.gsub, but it accepts an additional argument. Instead of replacing each match in the string, sub replaces the number of matches that you pass in as the optional 3rd argument (which defaults to 1). Let’s return to our original example:

string.sub(' ', '_');
// Returns "Laziness_always pays off now."

This time, only the first match was replaced. If we run it again and pass in the 3rd parameter we’ll see something different:

string.sub(' ', '_', 3);
 // Returns "Laziness_always_pays_off now."

Otherwise String.sub is identical to String.gsub.

String.scan

The scan method simply calls the String’s gsub method with the pattern and iterator function provided. This lets you loop through each match and do something with it:

string.scan(/\w+/, alert);    // Produces 5 alerts: "Laziness", "always", "pays", "off", "now"

Another use would be to get an array of all the items that matched:

var results = [];  string.scan(/\w+/, function(match){ results.push(match[0].toUpperCase()); });
 // results = ['LAZINESS', 'ALWAYS', 'PAYS', 'OFF', 'NOW']

For some reason, the scan method returns the String object split into an array of its characters.

String.truncate

This method works almost like you’d expect, with a slight quirk (in my opinion). The truncate method chops a string off to the number of characters you supply as the first argument:

string.truncate(15);
// Returns "Laziness alw..."

That’s almost what I expected to get, except there are only 12 characters from the original string instead of 15. That’s because there’s an optional second argument to truncate to append to the end of the string, and it counts as part of the returned string’s length. It defaults to ‘…’, but the following will yield the result I expected to see:

string.truncate(15, '');
 // Returns "Laziness always"

Template Class

Last we have a new Template class, which I think is a work of beauty. This class lets you set up a string template with variables to replace later, much like a PHP template or the server technology of your choice. The default variable substitution pattern is: #{variable_name}. Here’s how to create an object with the class:

var linkTemplate = new Template('<a href="#{href}">#{text}</a>');

You render the template by calling its evaluate method and passing in an object with property names matching the variables you used in the template:

linkTemplate.evaluate({href: 'http://www.google.com', text: 'The omnipotent one'});
// Returns "<a href="http://www.google.com">
The omnipotent one</a>"

It also works with an array:

var arrayTemplate = new Template('Original: #{0}, Sequel: #{1}');  arrayTemplate.evaluate(['Naked Gun', 'Naked Gun 2 1/2']);
 // Returns "Original: Naked Gun, Sequel: Naked Gun 2 1/2"

Customizing the Template Variable Pattern

Just because we can, let’s customize the Template class even further. Say you’ve already got a nice template, but it’s written in PHP using a short tag syntax. Being the lazy programmer you are, you can’t be bothered with rewriting this. Don’t worry, your hard work now will pay off with the potential for laziness later!

The second parameter to Template’s constructor is the regular expression pattern to use for the variable substitution. This parameter is optional and defaults to the Template.Pattern constant, which allows for the very nice #{variable} syntax. We can create our own regular expression to use for template variable substitution. Try the following:

Template.PhpPattern = /(^|.|\r|\n)(<\?=\s*\$(.*?)\s*\?>)/;

Now we can pull in a typical PHP template and let Prototype work its magic:

var phpTemplate = new Template('<div id="<?= $id ?>" class="<?= $class ?>"><?= $content ?></div>', Template.PhpPattern);
phpTemplate.evaluate({id: 'news', class: ['updated', 'arbitrary'].join(' '), content: '<p>No news is good news...</p>'});
// Returns "<div id="news" class="updated arbitrary"><p>No news is good news...</p></div>"

This might be useful if you are doing Ajax calls and returning JSON data a lot. You could create a Template class when the page loads using a small PHP template from your own site, then pass the JSON object you got from the Ajax request into the template’s evalute method. Of course, only do this if the PHP template file does not have any business/application logic that you don’t want prying eyes to see. Just remember that anything you give to JavaScript can be viewed by everyone. I recommend it only for simple templates that have simple variables, if you use it at all. You have been warned.

Even though I personally prefer to use simple PHP templates, I’ll give you a Smarty pattern to play with as well:

Template.SmartyPattern = /(^|.|\r|\n)(\{\$(.*?)\})/;

One important thing to note is that you should follow the existing Template.Pattern regular expression pattern’s structure of parenthesis. This structure follows one group to match before the variable, one group to match around the variable name, and the variable name itself. If you don’t follow the (beforePattern)(varSyntax(varName)) pattern, the template won’t replace your variable properly, because it relies on these parenthesis for the 1, 2, and 3 indexes.

Coming Full Circle

Now that I’ve shown you the Template class, I can put a nice cherry on top by showing you one more trick with String.gsub and String.sub. The second argument to these methods can also be a Template string:

string.gsub(/\s/, '#{0}_');
 // Returns "Laziness _always _pays _off _now."

When using a template string as the second parameter, keep in mind that the match’s index works just like the index of the array that would be passed if the second argument was a function. Here’s an example:

'Cory Hudson'.gsub(/(\w+) (\w+)/, '#{2}, #{1}');
 // Returns "Hudson, Cory"

Note that this Template pattern cannot be customized like it can be when you create an object from the Template class, so you’ll have to stick to the Ruby syntax when using gsub and sub. But emulating Ruby’s not such a bad thing, is it?

Strings Can Be Fun!

Even I had fun using Prototype’s latest additions to the native String object. They can save you some time while coding, and the fact that they are so flexible with their arguments is a nice bonus!

Source: CoryHudson.com

Tagged as: No tag for this post.
Filed under: Ajax, Javascript, Prototype by millisami  

Related Posts:

One Response to “Using Prototype’s New String Functions”

# Cody Swann , on September 15th, 2006 at 5:13 pm Said:

Nice work. Very useful.

MyAvatars 0.2

Have your say!

Clicky Web Analytics