.substr()
Published Jun 14, 2024
Contribute to Docs
The .substr()
method in JavaScript extracts a portion of a string, starting from a specified index position and extending for a specified number of characters. Indexing begins at zero. If a negative index is provided, it indicates the position from the end of the string, allowing extraction starting from the specified number of characters from the end.
Syntax
string.substr(start, length);
start
: The index position in the string where extraction begins. If negative, it counts from the end of the string.length
: The number of characters to extract. It is an optional parameter. If omitted, the extraction continues to the end of the string.
Example
The example below shows the use of .substr()
method in multiple ways:
// Extracting a portion of a string with a specified length.var sentence1 = 'The Intro to JavaScript is fun to learn.';console.log(sentence1.substr(4, 19));// Extracting a portion of a string _without_ a specified length.var sentence2 = 'The Intro to JavaScript is fun to learn.';console.log(sentence2.substr(4));// Extracting from the end of a string.var sentence3 = 'The Intro to JavaScript is fun to learn.';console.log(sentence3.substr(-27, 10));
The above example prints the following output on the console:
Intro to JavaScriptIntro to JavaScript is fun to learn.JavaScript
Codebyte Example
Note: The
.substr()
method does not change the original string.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours