var str = "I learn JavaScript";
// Let's extract a substring starting at first character index (zero)
alert( str.substring(0) );
Starting at the beginning, and not telling the method where to stop, we got the entire string back!var str = "I learn JavaScript"; // 5 first chars are highlighted
alert( str.substring(0, 5) );
var str = "I learn JavaScript"; // Next 5 first chars highlighted
alert( str.substring(5, 10) );
var str = "I learn JavaScript";
// Extract last six characters (highlighted above)
alert( str.substring( str.length-6 ) );
And now, the four characters before the last two: we count start and end indices from the end. var str = "I learn JavaScript";
// Extract the four letters highlighted above:
alert( str.substring( str.length-6 , str.length-2 ) );
Tip: end index minus start index give you the length of the substring you're about to extract.
var str = "I learn JavaScript";
alert( str.substring( str.length-1 ) );
var str = "I learn JavaScript";
str = str.substring( 8, 12 );
alert( str ); // str now equal to "Java"
$str = 'I learn PHP';
echo substr( $str, 2, 5 ); // returns 'learn'
substring() vs. substr(): JavaScript 1.2 included a method identical to PHP, also called substr(). It is now unfortunately deprecated (can't use safely, even if browsers still support it). It allowed negative start index (awesomely practical!), and an optional second argument for string length.
Sister method: slice() lets you extract substrings but allows negative start and end indices!