Java Reference
In-Depth Information
Character positions start at 0. If you don't include the second parameter, searching starts from the
beginning of the string.
The return value of indexOf() and lastIndexOf() is the character position in the string at which the
substring was found. Again, it's zero-based, so if the substring is found at the start of the string, then 0
is returned. If there is no match, the value -1 is returned.
For example, to search for the substring “Jeremy” in the string “Hello jeremy. How are you Jeremy”,
you may use the following code:
<script type=”text/javascript”>
var myString = “Hello jeremy. How are you Jeremy”;
var foundAtPosition;
foundAtPosition = myString.indexOf(“Jeremy”);
alert(foundAtPosition);
</script>
This code should result in a message box containing the number 26, which is the character position
of “Jeremy”. You might be wondering why it's 26, which clearly refers to the second “Jeremy” in the
string, rather than 6 for the fi rst “jeremy”. Well, this is due to case sensitivity again. It's laboring the
point a bit, but JavaScript takes case sensitivity very seriously, both in its syntax and when making com-
parisons. If you type IndexOf() instead of indexOf(), JavaScript will complain. Similarly, “jeremy”
is not the same as “Jeremy”. Remember that mistakes with case are very common and so easy to make,
even for experts, that it's best to be very aware of case when programming.
You've s e e n indexOf() in action, but how does lastIndexOf() differ? Well, whereas indexOf()
starts searching from the beginning of the string, or the position you specifi ed in the second parameter,
and works towards the end, lastIndexOf() starts at the end of the string, or the position you speci-
fi ed, and works towards the beginning of the string.
In the current example, you fi rst search using indexOf() , which fi nds the fi rst
“Jeremy” (changed to the correct case from the last example). The alert box displays
this result, which is character position 6 . Then you search using lastIndexOf() .
This starts searching at the end of the string, and so the fi rst “Jeremy” it comes to
is the last one in the string at character position 26 . Therefore, the second alert box
displays the result 26 .
<script type=”text/javascript”>
var myString = “Hello Jeremy. How are you Jeremy”;
var foundAtPosition;
foundAtPosition = myString.indexOf(“Jeremy”);
alert(foundAtPosition);
foundAtPosition = myString.lastIndexOf(“Jeremy”);
alert(foundAtPosition);
</script>
Search WWH ::




Custom Search