Java Reference
In-Depth Information
9
String Manipulation
In Chapter 4 you looked at the String object, which is one of the native objects that JavaScript
makes available to you. You saw a number of its properties and methods, including the following:
length
— The length of the string in characters
and charCodeAt() — The methods for returning the character or character
code at a certain position in the string
charAt()
indexOf()
and lastIndexOf() — The methods that allow you to search a string for the
existence of another string and that return the character position of the string if found
and substring() — The methods that return just a portion of a string
toUpperCase()
substr()
and toLowerCase() — The methods that return a string converted to
upper- or lowercase
In this chapter you'll look at four new methods of the String object, namely split(), match(),
replace(), and search(). The last three, in particular, give you some very powerful text-
manipulation functionality. However, to make full use of this functionality, you 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 enable
you to defi ne a pattern of characters, which can be used for text searching or replacement. Say, for
example, that you have a string in which you want to replace all single quotes enclosing text with
double quotes. This may seem easy — just search the string for ' and replace it with “ — but what
if the string is Bob O'Hara said “Hello”? You would not want to replace the single-quote
character in O'Hara. You can perform this text replacement without regular expressions, but it
would take more than the two lines of code needed if you do 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. You'll take a look at how they work in this
simpler context fi rst, to become familiar with the methods.
Search WWH ::




Custom Search