Java Reference
In-Depth Information
Now, say you want to replace May with June . You can use the replace() method like so:
Var myCleanedUpString = myString.replace("May", "June");
The value of myString will not be changed. Instead, the replace() method returns the value
of myString but with May replaced with June . You assign this returned string to the variable
myCleanedUpString , which will contain the corrected text:
"The event will be in June, the 21st of June"
the search() method
The search() method enables you to search a string for a particular piece of text. If the text is
found, the character position at which it was found is returned; otherwise, ‐1 is returned. The
method takes only one parameter, namely the text you want to search for.
When used with plaintext, the search() method provides no real benefit over methods like
indexOf() , which you've already seen. However, you see later that the power of this method
becomes apparent when you use regular expressions.
In the following example, you want to find 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
first 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
position 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 plaintext 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.
 
Search WWH ::




Custom Search