Stringing Things Along

Perform string manipulation tasks on the client with the JavaScript String object.

Getting Real

Most Real Programmers treat JavaScript like the poor cousin from the country - useful in certain situations, but not very important. Real Programmers aren't interested in a language whose primary application seems to be swapping one image with another, or drawing mouse trails across a Web page. Real Programmers have better things to do.

Well, I've got news for all your Real Programmers out there - JavaScript may be a small, not-very-exciting programming language limited to the client side of a Web transaction, but that's not a reason to count it out. Sure, it may not have the features and functions of PHP or Perl, but it sill comes with some very powerful tools - tools that can come in handy when you're trying to make your application more efficient by transferring computational load from the server to the client.

In order to illustrate what I mean, I'm going to be taking an in-depth look at one of the more powerful modules in JavaScript: its string library. I'm going to introduce you to the wonders of string concatenation, string comparison, string search and replace operations, and string formatting...all without writing a single line of Perl code.

In addition to providing a gentle introduction to JavaScript programming in general, this article will give you a broad overview of JavaScript's string manipulation capabilities, serving as both a handy reference and a tool to help you write more efficient code. Regardless of whether you're an Apprentice or a Real Programmer, you should find something interesting in here.

Elementary School

Let's start with the basics. In JavaScript, the term "string" refers to a sequence of characters. The following are all valid examples of strings:

"hey wassup?"

"I ROCK!"

"a long time ago in a galaxy far, far away"

String values can be assigned to a variable using the standard assignment operator.

<script language="Javascript">

var myStr = "Elementary, my dear Watson";

</script>

String values may be enclosed in either double quotes ("") or single quotes('') - the following variable assignments are equivalent:

<script language="Javascript">

var myStr = "Elementary, my dear Watson";

var myStr = 'Elementary, my dear Watson';

</script>

This comes in handy when you need to embed HTML code in your JavaScript strings, and don't want the various sets of quotes to conflict with each other. Consider the following example, which illustrates:

<script language="Javascript">

// bad
var myStr = "<a href="http://www.melonfire.com">Home</a>";

// good
var myStr = '<a href="http://www.melonfire.com">Home</a>';

</script>

You can also take the scenic route, and define a string using JavaScript's built-in String object, as below:

<script language="Javascript">

var myStr = "Elementary, my dear Watson";

// this is equivalent
var myStr = new String();
myStr = "Elementary, my dear Watson";

// and so is this
var myStr = new String("Elementary, my dear Watson");

</script>

When you do this, you create a proper JavaScript object, and thereby have access to all the methods and properties of that object. Note that it's not essential to create strings using the second technique outlined above; it's far more common (not to mention easier on your keyboard) to use the first one, because the JavaScript interpreter automatically converts string datatypes into string objects whenever necessary.

If you're a JavaScript newbie, this next example won't do much for you - but for those of you who are purists, this next code snippet will help in making the distinction between a datatype and an object clearer.

<script language="Javascript">

var myStr = "Hit me";
// this returns "string"
alert(typeof(myStr));

var myStr = new String("Hit me");
// this returns "object"
alert(typeof(myStr));

</script>

You can concatenate strings with the addition (+) operator - as the following example demonstrates:

<script language="Javascript">

var fname = "James";
var lname = "Bond";

// concatenate the two, separate with a space
var name = fname + " " + lname;

</script>

If your string contains quotes, carriage returns or backslashes, it's necessary to escape these special characters with a backslash.

<script language="Javascript">

// will cause an error due to mismatched quotes
var movie = 'Baby's Day Out';

// will be fine
var movie = 'Baby\'s Day Out';

</script>

Try it out yourself and see, and then flip the page to see how to dress up your strings.

When Size Does Matter

With the basics out of the way, let's now turn to some of the other string methods and properties available in JavaScript. One of the most common properties you'll find yourself using is the "length" property, which returns the length of a particular string. Consider the following example, which demonstrates:

<script language="Javascript">

// set string
var movie = "Four Weddings And A Funeral";

// print length
alert ("The length of the movie is " + movie.length + " characters");

</script>

This property can come in handy for operations which involve processing every character in a string (as you'll see shortly).

The String object also comes with a split() method, which can be used to decompose a single string into separate units on the basis of a particular separator value; these units are then placed into an array for further processing. Consider the following example, which demonstrates:

<script language="Javascript">

// set string
var friends = "Joey, Rachel, Monica, Chandler, Ross, Phoebe";

// split into array using commas
var arr = friends.split(", ");

// iterate through array and print each value
for (x=0; x<arr.length; x++)
{
    alert("Hiya, " + arr[x]);
}

</script>

Slice And Dice

Next up, the substring() method. As the name implies, this is the function that allows you to slice and dice strings into smaller strings. Here's what it looks like:

String.substring(start, end)

where "start" is the position to begin slicing at, and "end" is the position to end at (note that in JavaScript, the first character of a string is at position 0).

Here's an example which demonstrates how this works:

<script language="Javascript">

// set string
var str = "The horse munched pink flowers, waiting for the elephant to make its presence felt.";

// returns "pink flowers"
alert(str.substring(18, 30));

</script>

You can use this function to split a string into smaller chunks of a fixed size,

<script language="Javascript">

// set string
var str = "The horse munched pink flowers, waiting for the elephant to make its presence felt.";

// chunk size
var size = 9;

// counter
var count = 0;

/* returns
The horse
munched
pink flow
ers, wait
ing for t
he elepha
nt to mak
e its pre
sence fel
t.
*/
while ((size*count) < str.length)
{
        temp = str.substring(size*count, (size*count)+size);
        count++;
        document.write(temp + "\r\n");
}

</script>

You can also use the substring() method to extract a particular character from a string,

<script language="Javascript">

// set string
var str = "The horse munched pink flowers, waiting for the elephant to make its presence felt.";

// returns "p"
alert(str.substring(18,19));

</script>

Similar, though not identical, is the substr() method, which returns a substring, given the start position and the number of characters to be extracted. This method differs from the substring() method discussed above in that its second argument is not the end position, but the number of characters to be returned - as illustrated below:

<script language="Javascript">

// set string
var str = "Batman and Robin";

// returns "Batman"
alert(str.substr(0,6));

</script>

Building Character

You can use the indexOf() method to locate the first occurrence of a particular set of characters in a string

<script language="Javascript">

// set string
var str = "It's a bird! It's a plane! It's Superman!";

// returns 5
alert(str.indexOf("a"));

</script>

and the lastIndexOf() method to locate its last occurrence.

<script language="Javascript">

// set string
var str = "It's a bird! It's a plane! It's Superman!";

// returns 38
alert(str.lastIndexOf("a"));

</script>

Both these functions return the position of the substring in the original string, or -1 if no match is found.

Of course, the indexOf() method only returns the first match - but what if you need to find the second or third match? Simply add an argument to the method call, indicating where in the string the indexOf() method should begin searching:

<script language="JavaScript">

// set string
var str = "It's a bird! It's a plane! It's Superman!";

// returns 18
alert(str.indexOf("a", 10));

</script>

You can use the charAt() method to obtain the character at a particular index position within the string.

<script language="JavaScript">

// set string
var str = "Batman and Robin";

// returns "t"
alert(str.charAt(2));

</script>

A common application of the charAt() method is to iterate through a string, checking each character for validity against a pre-defined list. Consider the following example, which demonstrates how this works in the context of a password validator:

<html>
<head>

<script language="JavaScript">

// verify password string against allowed list of characters
function checkPassword()
{
    // error flag
    var error = 0;

    // list of valid characters
    var validChars = "abcdefghijklmnopqrstuvwxyz1234567890";

    // get value from form
    var password = document.forms[0].password.value;

    // iterate through string and check against allowed character list
    for (x=0; x<password.length; x++)
    {
        c = password.charAt(x);
        if (validChars.indexOf(c) == -1)
        {
            error = 1;
            break;
        }
    }

    // display appropriate message
    if (error == 1)
    {
        alert ("Error!");
        return false;
    }
    else
    {
        alert ("All OK!");
        return true;
    }
}
</script>

</head>

<body>

<form>
Enter password: <input name="password" type="text">
<br>
<input type="submit" value="Check!" onClick="checkPassword()">
</form>

</body>
</html>

Search And Destroy

You can also search for specific patterns in your strings with regular expressions, via the String object's search() method. Here's an example:

<script language="JavaScript">

var str = "johndoe@somedomain.com";

var pattern =
/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/;

// returns 0
alert(str.search(pattern));

</script>

The search() method returns the position of the substring matching the regular expression, or -1 if no match exists.

You can also perform a search-and-replace operation with the replace() method, which accepts both a regular expression and the value to replace it with. Here's how:

<script language="JavaScript">

// set string
var str = "yo ho ho and a bottle of gum";

// returns "yo ho ho and a bottle of rum"
alert(str.replace(/gum/gi, "rum"));

</script>

Bigger, Bolder, Better

Finally, if you're looking to perform a little cosmetic surgery on your strings, a good place to start is the toLowerCase() method, which comes in handy if you need to convert a string into entirely lower-case characters (there's also a toUpperCase() method, in case you change your mind)

<script language="JavaScript">

// set string
var str = "Jack Frost";

// returns "jack frost"
alert(str.toLowerCase());

// returns "JACK FROST"
alert(str.toUpperCase());

</script>

If you use HTML (I assume you do, otherwise you wouldn't have gotten this far), you'll be happy to hear that JavaScript provides a number of string formatting options equivalent to HTML's formatting tags. These options as exposed as methods of the String object. Here's an example which demonstrates:

<script language="Javascript">

// create a String object
var myStr = new String()
myStr = "Look, Ma, no hands";

// write it as is
document.write(myStr);
document.write("<br>");

// make it bolder...
document.write(myStr.bold());
document.write("<br>");

// ...bigger..
document.write(myStr.big());
document.write("<br>");

// ...more violent
document.write(myStr.strike());
document.write("<br>");

</script>

These methods allow developers to alter text formatting at runtime within the client, rather than with server-side code - this is good for a number of reasons, including the fact that user interface and presentation logic now lie in the domain of the client rather than the server.

Wanna use all those functions together? Sure!

<script language="Javascript">

// create a String object
var myStr = new String()
myStr = "Look, Ma, no hands";

// all at once
document.write(myStr.bold().big().strike());

</script>

JavaScript also comes with a bunch of other methods that allow you to alter the formatting of a string - play with them on your own time and see what they can do:

blink() - create a blinking string;

fixed() - create a string with a fixed-width font;

fontcolor() - set the font colour;

fontsize() - set the font size;

sub() - subscript the string;

sup() - superscript the string;

And that's about it. I hope you enjoyed this article, and that it offered you some insight into the string processing power at your disposal in JavaScript. Now, get out there and practice!

Note: All examples in this article have been tested on Internet Explorer 5.5 for Windows 98. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!

This article was first published on15 Jan 2003.