JavaScript substring()
The JavaScript substring()
method is used to return a portion of a string, starting from the specified index position and to the end of the string or to the specified index position. It is a commonly used string manipulation method in JavaScript.
Syntax
string.substring(startIndex, endIndex)
startIndex
: The index from which the extraction will begin. If the value is negative, it is treated as 0.endIndex
: The index position at which the extraction will end (up to, but not including). If the endIndex value is not specified, it will extract all characters from thestartIndex
to the end of the string.
Example
let s = "Hello World";
let sub1 = s.substring(1, 4); // "ell"
let sub2 = s.substring(4); // "o World"
let sub3 = s.substring(-3, 11); // "Hello Wor"
let sub4 = s.substring(12); // ""
Output
sub1 = "ell"
sub2 = "o World"
sub3 = "Hello Wor"
sub4 = ""