JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

Chapter 8: String Manipulation

Overview

In Chapter 4 we looked at the String object, which is one of the native objects that JavaScript makes available to us. We saw a number of its properties and methods, including the following:

In this chapter we'll look at four new methods of the String object, namely split(), match(), replace(), and search(). The last three, in particular, give us some very powerful text manipulation functionality. However, to make full use of this functionality, we need to learn about a slightly more complex subject.

The methods split(), match(), replace(), and search() can all make use of regular expressions, something JavaScript wraps up in an object called the RegExp object. Regular expressions allow you to define a pattern of characters, which can be used for text searching or replacement. Say, for example, that you had a string in which you wanted to replace all text enclosed in single quotes with double quotes. This may seem easy—just search the string for ' and replace it with "—but what if the string was Bob O'Hara said "Hello?" We would not want to replace the ' in O'Hara. Without regular expressions, this could still be done, but it would take more than the two lines of code needed if you use regular expressions.

Although split(), match(), replace(), and search() are at their most powerful with regular expressions, they can also be used with just plain text. We'll take a look at how they work in this simpler context first, to familiarize ourselves with the methods.


Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©