What is the use of substr() method in JavaScript?


substr()

substr() method extracts parts of a string, beginning at the character at the specified index, and returns the specified number of characters. It does not change the original string. 

Syntax

substr() method accepts two parameters one is start and other is length 

str.substr(start , length)

Arguments

   a) Start: start defines the starting index from where the sub string is to be extracted from the base string.

   b) length: length defines the number of characters to be extracted starting from the start in the given string. If the                          second argument to the function is undefined then all the characters from the start till the end of the length                     is extracted.

Example

In the following example, the arguments given are (7, 17). So, substr() method obtain sub string starting from index 7 to a length of 17 characters, there by giving "Spacex, Neuralink" as output.

  Live Demo

<html>
<body>
<p id="substring"></p>
<script>
   var str = "Tesla, Spacex, Neuralink, Solarcity";
   var res = str.substr(7,17);
   document.getElementById("substring").innerHTML = res;
</script>
</body>
</html>

Output

Spacex, Neuralink

Updated on: 30-Jul-2019

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements