Open In App

What is substr() Method in JavaScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 from startIndex 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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads