In JavaScript, the substring()
method is used to extract a portion of a string based on specified starting and ending indexes. It returns the extracted substring as a new string.
The syntax for the substring()
method is as follows:
string.substring(startIndex, endIndex)
Here’s a breakdown of the parameters:
startIndex
: The index at which the extraction should begin. This parameter is required and is a zero-based index, meaning the first character has an index of 0.endIndex
: The index at which the extraction should end. This parameter is optional. If not provided, thesubstring()
method will extract the substring from thestartIndex
to the end of the string. The character at theendIndex
will not be included in the extracted substring.
Here’s an example to illustrate the usage of substring()
:
var str = "Hello, World!";
var substring = str.substring(0, 5);
console.log(substring); // Output: Hello
In the above example, the substring()
method is used to extract the characters from index 0 to index 4 (excluding index 5) from the str
string. Therefore, the output is “Hello”.
It’s important to note that the substring()
method does not modify the original string. Instead, it returns a new string with the extracted portion. If you pass only one parameter (the startIndex
), it will extract the substring from that index to the end of the string. If the startIndex
is greater than the endIndex
, the method will swap the two values internally to ensure correct extraction.

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.