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

JavascriptObject Oriented ProgrammingProgramming

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.

<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
Published on 29-May-2019 08:28:45
Advertisements