The substring() method of the String class in JavaScript returns a new string containing characters of the calling string from (or between) the specified index (or indices).
There are 2 variations for the syntax of String.substring() method. They are:
substring(indexStart)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
indexStart | required | The index of the first character to include in the returned substring. If greater than indexEnd, the two indexes are swapped. |
This method returns a new string containing characters from the specified index to the end of the string.
Returns value of type String
.
substring(indexStart, indexEnd)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
indexStart | required | The index of the first character to include in the returned substring. If greater than indexEnd, the two indexes are swapped. |
indexEnd | optional | The index of the first character to exclude from the returned substring. If omitted, extracts characters to the end of the string. |
This method returns a new string containing characters from the specified start index up to, but not including, the specified end index.
Returns value of type String
.
In JavaScript, we can use the substring()
method to extract a substring starting from the specified index to the end of the string.
For example,
str
with the value 'Hello, world!'
.substring()
method with the start index 7
.'world!'
, is stored in the variable subStr
.subStr
to the console using console.log()
method.const str = 'Hello, world!';
const subStr = str.substring(7);
console.log(subStr);
'world!'
In this example, we use the substring()
method to extract a substring starting from the specified index and ending at the specified index.
For example,
str
with the value 'Hello, world!'
.substring()
method with the start index 7
and the end index 12
.'world'
, is stored in the variable subStr
.subStr
to the console using console.log()
method.const str = 'Hello, world!';
const subStr = str.substring(7, 12);
console.log(subStr);
'world'
This example demonstrates how the substring()
method swaps the indices if the start index is greater than the end index.
For example,
str
with the value 'Hello, world!'
.substring()
method with the start index 12
and the end index 7
.'world'
, is stored in the variable subStr
.subStr
to the console using console.log()
method.const str = 'Hello, world!';
const subStr = str.substring(12, 7);
console.log(subStr);
'world'
In this JavaScript tutorial, we learned about substring() method of String: the syntax and few working examples with output and detailed explanation for each example.