HTML and CSS Reference
In-Depth Information
Methods That Extract Substrings from a String. You might have to do more than
just find a substring within a string; you might need to extract that substring. For exam-
ple, we found the @ in the e-mail address, now we might want to get just the user name
or the server name or domain name. To do this, JavaScript provides methods such as
splice(), split(), charAt(), substr(), and substring() .
EXAMPLE 9.29
<html>
<head><title>Extracting Substrings</title></head>
<body bgcolor=lightgreen>
<font face="arial">
<big>Extracting substrings</big>
<small>
<script type="text/javascript">
1
var straddr = "DanielSavage@dadserver.org";
document.write("<br />His name is<em> " +
2
straddr.substr(0,6) + "</em>.<br />");
3
var namesarr = straddr.split("@" );
4
document.write( "The user name is<em> " + namesarr[0] +
"</em>.<br />");
5
document.write( "and the mail server is<em> " + namesarr[1]
+ "</em>.<br />");
6
document.write( "The first character in the string is <em>"
+ straddr.charAt(0) + "</em>.<br />");
7
document.write( "and the last character in the string is <em>"
+ straddr.charAt(straddr.length - 1)
+ "</em>.<br />");
</script>
</small>
</font>
</body>
</html>
EXPLANATION
1
A string is assigned an e-mail address.
2
The substr() starts at the first character at position 0, and yanks 6 characters from
the starting position. The substring is Daniel .
3
The split() method creates an array, called namesarr , by splitting up a string into
substrings based on some delimiter that marks where the string is split. This
string is split using the @ sign as its delimiter.
4
The first element of the array, namesarr[0] , that is created by the split() method is
DanielSavage , the user name portion of the e-mail address.
5
The second element of the array, namesarr[1] , that is created by the split() method
is dadserver.org , the mail server and domain portion of the e-mail address.
Continues
 
Search WWH ::




Custom Search