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

JavascriptObject Oriented ProgrammingProgramming


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. 


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

str.substr(start , length)


   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.


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

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


Spacex, Neuralink
Published on 29-May-2019 11:58:45