Java Reference
In-Depth Information
In the following example, you want to fi nd out if the word Java is contained within the string called
myString.
var myString = “Beginning JavaScript, Beginning Java, Professional JavaScript”;
alert(myString.search(“Java”));
The alert box that occurs will show the value 10, which is the character position of the J in the fi rst
occurrence of Java, as part of the word JavaScript.
The match() Method
The match() method is very similar to the search() method, except that instead of returning the posi-
tion at which a match was found, it returns an array. Each element of the array contains the text of each
match that is found.
Although you can use plain text with the match() method, it would be completely pointless to do so.
For example, take a look at the following:
var myString = “1997, 1998, 1999, 2000, 2000, 2001, 2002”;
myMatchArray = myString.match(“2000”);
alert(myMatchArray.length);
This code results in myMatchArray holding an element containing the value 2000. Given that you
already know your search string is 2000, you can see it's been a pretty pointless exercise.
However, the match() method makes a lot more sense when you use it with regular expressions. Then
you might search for all years in the twenty-fi rst century — that is, those beginning with 2. In this
case, your array would contain the values 2000, 2000, 2001, and 2002, which is much more useful
information!
Regular Expressions
Before you look at the split(), match(), search(), and replace() methods of the String object
again, you need to look at regular expressions and the RegExp object. Regular expressions provide a
means of defi ning a pattern of characters, which you can then use to split, search for, or replace charac-
ters in a string when they fi t the defi ned pattern.
JavaScript's regular expression syntax borrows heavily from the regular expression syntax of Perl, another
scripting language. The latest versions of languages, such as VBScript, have also incorporated regular
expressions, as do lots of applications, such as Microsoft Word, in which the Find facility allows regu-
lar expressions to be used. The same is true for Dreamweaver. You'll fi nd that your regular expression
knowledge will prove useful even outside JavaScript.
Regular expressions in JavaScript are used through the RegExp object, which is a native JavaScript object,
as are String, Array, and so on. There are two ways of creating a new RegExp object. The easier is with
a regular expression literal, such as the following:
var myRegExp = /\b'|'\b/;
Search WWH ::




Custom Search