Java Reference
In-Depth Information
do this in the for loop, where instead of starting at 0 and working up as you usually do, you start at a
number greater than 0 and decrement until you reach 0, at which point you stop looping.
for (indexCount = numberOfParts - 1; indexCount >= 0; indexCount--)
{
reversedString = reversedString + textArray[indexCount];
if (indexCount > 0)
{
reversedString = reversedString + “\n”;
}
}
Finally, you assign the text in the
textarea
element to the new string you've built.
textAreaControl.value = reversedString;
}
After you've looked at regular expressions, you'll revisit the
split()
method.
The replace() Method
The
replace()
method searches a string for occurrences of a substring. Where it fi nds a match for this
substring, it replaces the substring with a third string that you specify.
Let's look at an example. Say you have a string with the word
May
in it, as shown in the following:
var myString = “The event will be in May, the 21st of June”;
Now, say you want to replace
May
with
June
. You can use the
replace()
method like so:
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 plain text, the
search()
method provides no real benefi t over methods like
indexOf()
,
which you've already seen. However, you'll see later that it's when you use regular expressions that the
power of this method becomes apparent.