HTML and CSS Reference
In-Depth Information
EXAMPLE
9.28
<html>
<head><title>String Manipulation</title></head>
<body>
<h2>Working with String Manipulation Methods</h2>
<script type="text/javascript">
function break_tag(){
document.write("<br />");
}
document.write("<h3>");
1
var str1 = new String("The merry, merry month of June...");
document.write("In the string:<em> "+ str1 );
2
document.write("</em> the first 'm' is at position " +
str1.indexOf("m")
);
break_tag();
3
document.write("The last 'm' is at position " +
str1.lastIndexOf("m")
);
break_tag();
4
document.write("<em>str1.substr(4,5)</em> returns<em> " +
str1.substr(4,5)
);
break_tag();
document.write
(str1.toUpperCase()
);
document.write("</h3>");
</script>
</body>
</html>
EXPLANATION
1
A new
String
object is created with the
String()
constructor.
2
The
indexOf() String
method returns the index value where “m” is first encoun-
tered in the string starting at the first character, position 0.
3
The
lastIndexOf()
method returns the index position of the last occurrence of “m”
in the string starting from the left from position 0.
4
Starting at position 4, the
Substr
method returns 5 characters.
Figure 9.33
Output from Example 9.28.