substring vs slice

Substring() vs Slice() in JavaScript

What is substring()?

substring() method returns part of the string from start index upto end index but excluding the endindex. It extracts characters between two indices from a string and return the substring. It does not change the original string.

Syntax:
substring(indexStart)
substring(indexStart, indexEnd)

Parameters:

indexStart – Index of first character to include in substring.

indexEnd – It is optional. It denotes the first character to exclude from the returned string.

When indexEnd is not there, the substring() method returns characters upto the end of the string.

Return value – A new sub string containing part of original string.

What will happen if both index start and end are same?

const str = ‘Abaython’
str.substring(3,3)

When both start and end index are same will return an empty string.

If start index greater than end index?

const str = ‘Abaython’
str.substring(4,2)
Output:

ay

Here it will simply swap the parameters as,

str.substring(2,4)

So, the output is ay.

If indexEnd is omitted?

const str = ‘Abaython’
str.substring(4)
Output:

thon

Here it will return upto the end of the string starting from index 4

Substring() vs slice()

Though in both methods the parameters are same, the main difference is using negative values.

In substring() method negative values are considered as zero.

const s = 'Abaython';
console.log(s.substring(-4,5))
Output:

Abayt

Here -4 is considered as 0 and returns from the start of the string.

Keypoints to note:

Similarities:

  • In both methods the parameters are same. If start and end index are equal both returns an empty string.
  • If end index is omitted then the characters are extracted upto the end of the string.
  • Any parameter greater than string length then string length is used instead.
  • NaN treated as 0.

Differences:

  • In case of startindex > endindex,

Substring() method swaps the parameters.

Slice() method returns empty string

  • If any argument has negative values,

Substring() method treats them as 0

Slice() method counts from the end of the string for negative values