1.2 Accessing Substrings
NN 2, IE 3
Use the substring( ) method (in all scriptable browsers) to copy a segment starting at a particular location and ending either at the end of the string (omitting the second parameter does that) or at a fixed position within the string, counting from the start of the string:
var myString = "Every good boy does fine."; var section = myString.substring(0, 10); // section is now "Every good"
var myString = "Every good boy does fine."; var section = myString.slice(11, -6); // section is now "boy does"
Use the nonstandard, but widely supported, variant called substr( ) to copy a segment starting at a particular location for a string length (the second parameter is an integer representing the length of the substring):
var myString = "Every good boy does fine."; var section = myString.substr(6, 4); // section is now "good"
If the sum of the two arguments exceeds the length of the string, the method returns a string from the start point to the end of the string.
Parameters for the ECMA-compatible slice( ) and substring( ) methods are numbers that indicate the zero-based start and end positions within the string from which the extract comes. The first parameter, indicating the start position, is required. When you use two positive integer values for the slice( ) method arguments (and the first argument is smaller than the second), you receive the same string value as the substring( ) method with the same arguments.
Note that the integer values for substring( ) and splice( ) act as though they point to spaces between characters. Therefore, when a substring( ) method's arguments are set to 0 and 4, it means that the substring starts to the right of the "zeroeth" position and ends to the left of the fourth position; the length of the string value returned is four characters, as shown in Figure 1-1.
None of the substring methods modifies the original string object or value in any way. This is why you must capture the returned value in a variable, or apply the returned value as an argument to some other function or method.
1.2.4 See Also
Recipe 1.5 for testing whether a string contains a substring.