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.
JavaScript str.substr() Function
The str.substr() function returns the specified number of characters from the specified index from the given string.
Syntax:
str.substr(start, len);
Example: This example uses only one parameter for both functions and produces the same output.
const str1 = "GeeksForGeeks" ;
const substrResult = str1.substr(7); const substringResult = str1.substring(7); console.log( "Str.substr(7) =" , substrResult);
console.log( "Str.substring(7) =" , substringResult);
|
Str.substr(7) = rGeeks Str.substring(7) = rGeeks
JavaScript str.substring() Function
This function gets the characters from a string, between two specified indices, and returns the new string.
Syntax:
str.substring(start, end);
Example: This example uses the parameter (3, 7) for both functions and returns the output.
const str1 = "GeeksForGeeks" ;
const substrResult = str1.substr(3, 7); const substringResult = str1.substring(3, 7); console.log( "Str.substr(3, 7) =" , substrResult);
console.log( "Str.substring(3, 7) =" , substringResult);
|
Str.substr(3, 7) = ksForGe Str.substring(3, 7) = ksFo
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.
|