What is substr() Method in JavaScript ?
In JavaScript, the substr()
method is used to extract a substring from a string, starting at a specified position and containing a specified number of characters.
Syntax:
string.substr(startIndex, length)
string
: The string from which to extract the substring.startIndex
: The index at which to begin extracting characters. If negative, it is treated as(string.length + startIndex)
.length
(optional): The number of characters to extract. If omitted, all characters fromstartIndex
to the end of the string are included in the substring.
Example: Here, the substr()
method is called on the str
string with the startIndex
of 7
and length
of 5
. This extracts a substring starting from the character at index 7
(which is “W”) and containing 5
characters thereafter. The resulting substring is "World"
.
Javascript
const str = "Hello, World!" ; const substring = str.substr(7, 5); console.log(substring); // Output: "World" |
Output
World
Contact Us