![]() |
VOOZH | about |
The substr() method in JavaScript extracts a portion of a string, starting from a specified index position and extending for a given number of characters.
This method was traditionally used to extract a part of a string, however, the method is now considered outdated, and the substring() or slice() methods are recommended as alternatives.
str.substr(start, length)Returns a string that is part of the given string. If the length is 0 or a negative value then it returns an empty string. If we want to extract the string from the end then use a negative start position.
Example 1: Extract Substring using substr()
This code demonstrates the usage of the substr() method in JavaScript. It extracts a substring from the original string starting from the specified index (5 in this case) till the end. The extracted substring is then printed.
a great day.
Example 2: Negative Length in substr() Method
This code demonstrates an attempt to use a negative length parameter in the substr() method, which is invalid. JavaScript substr() method expects a positive length value, resulting in an empty string when provided with a negative value.
Example 3: Extracting Substring from End Using substr()
This code snippet utilizes the substr() method to extract a substring from the end of the original string 'It is a great day.'. The negative index -7 indicates starting from the 7th character from the end, and 6 characters are extracted.
at day
Now to use modern methods like substring() or slice() you can follow these articles.
We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.