JavaScript substring() Method
This tutorial introduces the substring() method, from the JavaScript String object. The substring() method is designed to extract a substring of text from another string, while not modifying the original string. The substring() method takes at least one argument (to take a substring ending with the end of the original string), and an optional second argument indicating the position index at which the extracted substring should stop.
Related string method:
The substr() method extracts a substring from a fixed start index and relative string length.
Using the substring() Method with One Argument
In the script below, we will extract a substring using only one argument:
var carter = "I learn JavaScript.";
alert( carter.substring(8) );
By only passing one argument (the start position index), the substring() method extracts characters until it reaches the end of the string on which it is applied:
In this respect, the substring() method behaves exactly like the substr() method, when only the start position index is passed.
Using the substring() Method with Two Arguments
The substring() method accepts a second optional argument: it indicates the point at which it should stop extracting characters (in other words, the second argument indicates the end position index).
var carter = "I learn JavaScript.";
alert( carter.substring(8,12) );
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 substring() Method
Interactively test the substring() method by editing the JavaScript code below and clicking the Test substring() Method button.
Browser support for JavaScript substring() method | |||
---|---|---|---|