Skip to content

JavaScript substr() | String method

  • by

Using the JavaScript substr() String method you can get the portion of the string, starting at the specified index and extending for a given number of characters afterward.

substr(start)
substr(start, length)

This method returns a part of a string and does not change the original string. To extract characters from the end of the string, use a negative start position.

Note: If length is 0 or negative, an empty string is returned.

JavaScript substr()

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    let text = "Hello world!";
    let res = text.substr(1, 4);
    console.log(res);

    console.log(text.substr(2));

    //Only the first
    console.log(text.substr(0, 1));

    //Only the last:
    console.log(text.substr(-1, 1));

  </script>
</body>
</html>

Output:

JavaScript substr String method

More examples

const aString = 'Mozilla';

console.log(aString.substr(0, 1));   // 'M'
console.log(aString.substr(1, 0));   // ''
console.log(aString.substr(-1, 1));  // 'a'
console.log(aString.substr(1, -1));  // ''
console.log(aString.substr(-3));     // 'lla'
console.log(aString.substr(1));      // 'ozilla'
console.log(aString.substr(-20, 2)); // 'Mo'
console.log(aString.substr(20, 2));  // ''

Do comment if you have any doubts or suggestions on this Js string method tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *