The two popular methods of javascript strings slice() and substring() are very similar, but there are a few differences. This article discusses the differences between the slice() and substring() methods using various scenarios and example illustrations.

Let’s start looking into the syntax of both:

syntax of slice():-

slice(startIndex, endIndex)

Here,

  • The indexes of the slice() method are zero-based.
  • The startIndex specifies from where the extraction will begin. The extracted string includes the character at startIndex.
  • The endIndex specifies to end the extraction before the endIndex. The extracted string excludes the character at endIndex. Also, the endIndex is optional.

syntax of substring():-

substring(startIndex, endIndex)

Here,

  • The indexes of the substring() method are zero-based.
  • The startIndex is the first argument of the method and specifies from where the extraction will begin. The extracted string includes the character at startIndex.
  • The endIndex is the second argument of the method and specifies to end the extraction before the endIndex. The extracted string excludes the character at endIndex. Also, the endIndex is optional.

Differences between slice() and substring()

1. Negative indexes:-

slice(): If startIndex is negative, it will be treated as string.length + startIndex. If the endIndex is negative, it will be treated as string.length + endIndex.

substring(): If startIndex is negative, it will be treated as 0. If the endIndex is negative, it will be treated as 0.

Example illustration for slice() method:

let dummyString = 'Javascript'
dummyString= dummyString.slice(-6,11) // equivalent to slice(5,11)
console.log( dummyString )

Output:-

script

Example illustration for substring() method:

let dummyString = 'Javascript'
dummyString= dummyString.substring(-6,11) // equivalent to substring(0,11)
console.log( dummyString )

Output:-

Javascript

2. When startIndex > endIndex:-

slice(): If startIndex is greater than endIndex, substring() will swap both the arguments.

substring(): If startIndex is greater than endIndex, slice() returns an empty string.

Example illustration for slice() method:

let dummyString = 'Javascript'
dummyString= dummyString.slice(11,4) // returns empty string
console.log( dummyString )

Output:-


Example illustration for substring() method:

let dummyString = 'Javascript'
dummyString= dummyString.substring(11,4) // arguments are swapped
console.log( dummyString )

Output:-

script

Read More:

I hope this article helped you understand the subtle differences between the substring() and slice() method of javascript.