Think JavaScript's only good for image swaps and tickertapes?Think again - the language comes with a powerful String() objectdesigned to help you quickly and efficiently perform string manipulationtasks in the client. This article explains how, with illustrations andcode samples.
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>