Open In App

JavaScript String substr() Method

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:

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 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 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 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.

Article Tags :