HomeJavaScript Page 6 - Understanding the JavaScript RegExp Object
In Splits - JavaScript
Need to match and replace patterns on a Web page? You don't need Perl or PHP - JavaScript can do the job just as well. In this article, find out how, with an introduction to the JavaScript RegExp object and its methods. After reading this tutorial, I'm pretty sure you're going to look at JavaScript in a different light. The language ins't the one most commonly associated with image swaps and browser detection, but it serves as a powerful tool to help you execute pattern-matching tasks in the client quickly and efficiently.
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>
Up until JavaScript 1.1, you could only use string values as separators. JavaScript 1.2 changed all that; now, you can even split a string on the basis of a regular expression.
To understand this better, consider the following string, which illustrates a common problem: unequal whitespace between separated values:
Neo
| Trinity |Morpheus | Smith| Tank
Here, the | character is used to separate the various names. However, the space between the various | is unequal - which means that before you can use the individual elements of the string, you will need to trim the additional space around them. Splitting by using a regular expression as the separator is an elegant solution to the problem - as you can see from the updated listing below: