In this section, we will learn what the substr() method is and how to use it.
JavaScript String substr() Method
The string substr() method is used to extract a sub-string from another string value.
Note: this method won’t change the original text content.
JavaScript String substr() Syntax
string.substr(start, length)
String substr() Method Parameters:
The method takes two arguments:
- The first argument is the index number from which the extraction should start.
Note: if the value is negative, that means start from the last character of the string value and count backward to declare the start index position.
Note: the first character in a string value starts from the index number 0.
- The second argument is the number of characters that we want to extract. This value is optional and if ignored, that means all the characters from the start-index to the end of the string value.
Note: if we use a negative number as the second argument, it will be treated as 0. So the final result will be an empty string.
String substr() Method Return Value:
The return value of this method is a new sub-string value that was extracted from the original text content.
Example: using substr() method in JavaScript
console.log("This is for test".substr(5,2));
Output:
is
Example: JavaScript substr method
const answer = 42; console.log("This is for test".substr(-4,4));
Output:
test
Because we used the negative number as the first argument, the starting position is declared from the end of the string towards the beginning. The value here is -4, so then count 4 characters backwards from the end of the string-value and that will be the starting position of the extraction.