JavaScript substr(): Extract a substring from a string

The JavaScript substr() method is used to extract a substring from a specified position in a specified string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "JavaScript is Fun. Is not it?";

      let mySubString = myString.substr(19);
      document.getElementById("xyz").innerHTML = mySubString;
   </script>
   
</body>
</html>
Output

Since indexing starts with 0. Therefore, in the string "JavaScript is Fun. Is not it?"

A similar 'I' is at index no. 19. Therefore, a substring starting from index no. 19 was extracted from the string. That is, after index no. 18, the remaining or all characters of the specified string were extracted.

JavaScript substr() syntax

The syntax of the substr() method in JavaScript is:

string.substr(startIndex, numberOfCharacters)

The startIndex argument is required. Whereas the numberOfCharacters argument is optional and its default value is the length of the string (string.length - 1).

The numberOfCharacters argument refers to a number, used when we need to extract only a particular number of characters from the specified startIndex position. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "JavaScript is Fun. Is not it?";

      let mySubString = myString.substr(19, 2);
      document.getElementById("xyz").innerHTML = mySubString;
   </script>
   
</body>
</html>
Output

Note: The string.substr(0, 1) returns the first character of the string.

Note: The string.substr(string.length-1, 1) returns the last character of the string.

Note: The string.substr(-3, 3) returns the last three characters of the string.

Note: The string.substr(-7, 3) returns the three characters starting from the seventh position from last. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "JavaScript is Fun. Is not it?";

      let mySubString = myString.substr(-7, 3);
      document.getElementById("xyz").innerHTML = mySubString;
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!