substr()

Difference between substr and substring

What is substr() method?

Substr() method returns a particular number of characters starting from specified index.

Syntax:
substr(startIndex, Length)
substr(startIndex)

startIndex – index of first character to include in the return string

length – It is optional determines the number of characters to extract.

Return value – A new string containing the specified part of given string.

Example:
let str = "Abaython";
console.log(str.substr(1,2));
console.log(str.substr(-2,2));
console.log(str.substr(1));
console.log(str.substr(-1,2));
Output:

ba

on

baython

n

Points to note:
  • start >= str.length, an empty string is returned.
  • If start < 0, the index starts counting from the end of the string. More formally, in this case the substring starts at max(start + str.length, 0).
  • If start is omitted or undefined, it’s treated as 0.
  • If length is omitted or undefined, or if start + length >= str.length, substr() extracts characters to the end of the string.
  • If length < 0, an empty string is returned.
  • For both start and length, NaN is treated as 0.

Though substr() is not strictly a deprecated function, it is considered a legacy function and you should avoid using it as possible as you can. It is not part of JavaScript and may be removed in the future. So, you can use the substring() method instead.

Difference

The main difference lies in the parameter the second parameter in substr() method indicates the number of characters to extract whereas in substring() the second parameter denotes the index upto which we need to extract excluding the particular index.

For negative values in parameters in substr() for first argument index counted from back and second argument is considered as zero. In substring() simply considered zero.