Difference between substr() and substring()
Feature | substr() |
substring() |
---|---|---|
Syntax | str.substr(start, length) |
str.substring(start, end) |
Parameters | start : Starting index |
start : Starting index |
Length | length : Number of characters to extract |
end : Ending index (exclusive) |
Negative Index | Accepts negative start (counts from the end) |
Does not accept negative start or end |
Behavior with Negative Index | If start is negative, it’s treated as str.length + start . If length is negative, it’s ignored. |
If either start or end is negative, they are treated as 0. |
Handling Omitted Parameters | If length is omitted, extracts characters to the end of the string. |
If end is omitted, extracts characters to the end of the string. |
Difference between substr() and substring() in JavaScript
In JavaScript Both of the functions are used to get the specified part of the string, But there is a slight difference between them. substr() and substring() are string methods used to extract parts of a string. The main difference is that substr() accepts a length parameter, while substring() accepts start and end indices.