JavaScript substr() | Extract Substring from a String

The JavaScript substr() method is used to extract substring from specified position in 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?"

  • 'J' is at index no.0
  • 'a' is at index no.1
  • 'v' is at index no.2
  • and so on

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

JavaScript substr() Syntax

The syntax of 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 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 3 characters of the string.

Note: The string.substr(-7, 3) returns the 3 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 »



Like/Share Us on Facebook 😋