The substr()
method in JavaScript returns a part of a string from the specified index without changing the original string.
The syntax of this method is as follows:
string.substr(startIndex, length)
The substr()
method takes two parameters, one mandatory and one optional.
startIndex
(required): The integer value of the starting index, i.e., where the substring extraction should start.length
(optional): The integer value of the length of the substring that needs to be extracted. If length
is not specified, the string is extracted until the end.The return value is a string that is a part of the original string.
In the first example below, the substring is extracted without specifying its length, and so the complete string starting from the specified index is taken out.
In the second example, when the length of the substring is specified, the function extracts the part starting from the given index until the required length is achieved.
// Example no.1// extracting a substring without specifying lengthlet str = "Welcome to Educative";let x = str.substr(4);console.log(x)// Example no.2// extracting a substring by specifying lengthlet y = str.substr(11,3);console.log(y)