The substr() method of the String class in JavaScript returns a portion of the string, starting at the specified index and extending for a given number of characters afterwards.
There are 2 variations for the syntax of String.substr() method. They are:
substr(start)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
start | required | The index of the first character to include in the returned substring. A negative index counts back from the end of the string. |
This method returns a portion of the string starting from the specified index to the end of the string.
Returns value of type String
.
substr(start, length)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
start | required | The index of the first character to include in the returned substring. A negative index counts back from the end of the string. |
length | optional | The number of characters to include in the returned substring. If omitted, it extracts characters to the end of the string. |
This method returns a portion of the string starting from the specified index and extending for the specified number of characters.
Returns value of type String
.
In JavaScript, we can use the substr()
method to extract a substring starting from the specified index to the end of the string.
For example,
str
with the value 'Hello, world!'
.substr()
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.substr(7);
console.log(subStr);
'world!'
In this example, we use the substr()
method to extract a substring starting from the specified index and extending for the specified number of characters.
For example,
str
with the value 'Hello, world!'
.substr()
method with the start index 7
and the length 5
.'world'
, is stored in the variable subStr
.subStr
to the console using console.log()
method.const str = 'Hello, world!';
const subStr = str.substr(7, 5);
console.log(subStr);
'world'
This example demonstrates how to use the substr()
method with a negative start index to extract a substring from the end of the string.
For example,
str
with the value 'Hello, world!'
.substr()
method with the start index -6
to extract the last six characters.'world!'
, is stored in the variable subStr
.subStr
to the console using console.log()
method.const str = 'Hello, world!';
const subStr = str.substr(-6);
console.log(subStr);
'world!'
In this JavaScript tutorial, we learned about substr() method of String: the syntax and few working examples with output and detailed explanation for each example.