JavaScript Substr Method: If you wanted to pulls out a portion of a string and assign that cut-out part to another variable or use it in an expression, you would use the JavaScript Substr Method.
Syntax of JavaScript String substr() Method:
string.substr(start, length)
The first parameter start is the starting index and the second parameter is the length of the substring. Since you’re string can’t have a negative length, you can’t use a negative number for the second parameter (you can use a negative number for the first parameter, though). Of course, that second parameter is optional, if you want the rest of the string.
JavaScript Substr Method differs from String JavaScript substring() Method in two basic ways. One, in substring() the start position cannot be negative, that is, it must be 0 or greater. Two, the second parameter in substring() indicates a position to go to, not the length of the new substring.
<html> <head> <title>Example of JavaScript Substr Method</title> </head> <body> <font face="arial" size="+1"> Example of Substr() <font size="-1"> <script language="JavaScript"> var straddr = "ecomputernotes@gmail.com"; document.write("<br>His name is<em> " + straddr.substr(0,14) + "</em>.<br>"); var namesarr = straddr.split("@" ); document.write( "The user name is<em> " + namesarr[0] + "</em>.<br>"); document.write( "and the mail server is<em> " + namesarr[1] + "</em>.<br>"); document.write( "The first character in the string is <em>" + straddr.charAt(0)+ "</em>.<br>"); document.write( "and the last character in the string is <em>" + straddr.charAt(straddr.length - 1) + "</em>.<br>"); </script> </body> </html>
EXPLANATION
1. A string is assigned an e-mail address.
2. The JavaScript Substr Method starts at the first character at position 0, and yanks 14 characters from the starting position. The substring is ecomputernotes.
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 ecomputernotes, 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 gmail.com, the mail server and domain portion of the e-mail address.
6. The charAt() method returns the character found at a specified position within a string; in this example, position 0. Position 0 is the first character in the string, a letter e.
7. By giving the charAt() method the length of the string minus 1, the last character in the string is extracted, a letter m.