Open In App

JavaScript String substr() Method

Last Updated : 14 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The substr() method in JavaScript extracts a portion of a string, starting from a specified index position and extending for a given number of characters.

Syntax:

str.substr(start , length)

Parameters:

  • start: It defines the starting index from where the substring is to be extracted from the base string.
  • length: It defines the number of characters to be extracted starting from the start in the given string. If the second argument to the method is undefined then all the characters from the start till the end of the length are extracted.

Return value:

returns a string that is part of the given string. If the length is 0 or a negative value then it returns an empty string. If we want to extract the string from the end then use a negative start position.

JavaScript String substr() Method Examples

Example 1: Extract Substring using substr()

This code demonstrates the usage of the substr() method in JavaScript. It extracts a substring from the original string starting from the specified index (5 in this case) till the end. The extracted substring is then printed.

JavaScript
// JavaScript to illustrate substr() method

function func() {

    // Original string
    let str = 'It is a great day.';
    let sub_str = str.substr(5);
    console.log(sub_str);
}

func();

Output
 a great day.

Example 2: Negative Length in substr() Method

This code demonstrates an attempt to use a negative length parameter in the substr() method, which is invalid. JavaScript substr() method expects a positive length value, resulting in an empty string when provided with a negative value.

JavaScript
// JavaScript to illustrate substr() method

function func() {

    // Original string
    let str = 'It is a great day.';

    let sub_str = str.substr(5, -7);
    console.log(sub_str);
}
func();

Output

Example 3: Extracting Substring from End Using substr()

This code snippet utilizes the substr() method to extract a substring from the end of the original string ‘It is a great day.’. The negative index -7 indicates starting from the 7th character from the end, and 6 characters are extracted.

JavaScript
// JavaScript to illustrate substr() method

function func() {

    // Original string
    let str = 'It is a great day.';

    let sub_str = str.substr(-7, 6);
    console.log(sub_str);
}

func();

Output
at day

We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.

Supported Browsers:

We have a Cheat Sheet on JavaScript where we covered all the important topics of JavaScript to check those please go through JavaScript Cheat Sheet – A Basic Guide to JavaScript.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads