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:
length—the length of the string in characters
charAt() and charCodeAt()—the methods for returning the character or character code at a certain position in the string
indexOf() and lastIndexOf()—the methods that allow the searching of a string for the existence of another string and return the character position of the string if found
substr() and substring()—the methods that return just a portion of a string
toUpperCase() and toLowerCase()—the methods that return a string converted to upper- or lowercase
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.