JavaScript substr() Method
This tutorial presents the substr() method, part of JavaScript's String object. The substr() method is used to extract substrings from the string on which it is called; unlike the more common substring() method, substr() takes as second optional argument a relative length, while accepting a position index as first argument - like the substring() method.
Related string method:
The substring() method extracts a substring from a fixed start and end position index.
Using the substr() Method with One Argument
The substr() method requires at least one argument, an integer, which indicates the starting position index for the substring to extract.
var carter = new String("I learn JavaScript.");
alert( carter.substr(8) );
Omitting a second argument instructed the substr() method to extract a sub-string going from the supplied position index to the end of the string:
The substr() method's optional second argument (also an integer) is designed to limit the length of the substring to extract.
Using the substr() Method with Two Arguments
Let us re-use our previous script, this time by supplying a length-limiting second argument to the substr() method:
var carter = new String("I learn JavaScript.");
alert( carter.substr(8,4) );
As expected, the resulting string was of length 4:
JavaScript's charAt(), substr(), and substring() Methods
The JavaScript string objects includes three methods that allow you to extract substrings of text: the charAt() method (for a single character), the substr() method (fixed start index and relative length), and the substring() method (for a fixed start and end index positions).
The script below how to obtain the same result from each of the three methods:
var carter = "I learn JavaScript.";
// Let's extract the "J" in "JavaScript"
var outCode;
outCode = carter.charAt(8) +"\n";
outCode += carter.substr(8,1) +"\n";
outCode += carter.substring(8,9);
alert( outCode );
After storing the results, separated by a new line character, the last line of code produces the following result:
Test the substr() Method
Interactively test the substr() method by editing the JavaScript code below and clicking the Test substr() Method button.
Browser support for JavaScript substr() method | |||
---|---|---|---|