Javascript: slice() method

This article discusses the syntax and functioning of the slice() method in javascript including various examples for illustration purposes.

slice()

Javascript’s slice() method extracts parts of string and returns them in a new string. The slice() method does not modify the original string.

Syntax of slice():-

slice(startIndex, endIndex)

Here,

  • The index of slice() starts from zero.
  • The startIndex specifies from where the extraction will begin. The extracted string includes the character at startIndex.
  • If startIndex value is negative, it is treated as string.length + startIndex
  • The endIndex specifies to end the extraction before the endIndex. The extracted string excludes the character at endIndex.
  • The endIndex is optional.
  • If endIndex value is negative, it is treated as string.length + endIndex
  • If startIndex > endIndex, an empty string is returned.

Example-1 of slice():-

let dummyString = 'Javascript*'
dummyString= dummyString.slice(0,4)
console.log( dummyString )

Output:-

Java

Example-2 of slice():-

let dummyString = 'Javascript*'
dummyString= dummyString.slice(0,-1)
console.log( dummyString )

Explanation:-

In the above code, the substring is formed from the beginning of the original string. The endIndex is treated as 11 + (-1) -> 10. Therefore slice(0,10).

Output:-

Javascript

Example-3 of slice():-

let dummyString = 'Javascript*'
dummyString= dummyString.slice(-1,11)
console.log( dummyString )

Explanation:-

In the above code, The startIndex is treated as 11 + (-1) -> 10. Therefore slice(10,11) , which leaves only the last character that is ‘*’.

Output:-

*

Example-4 of slice():-

let dummyString = 'Javascript*'
dummyString= dummyString.slice(11,8)
console.log( dummyString )

Explanation:-

In the above code, The startIndex is greater than the endIndex. Therefore slice(11,8) will return an empty string.

I hope this article helped you to understand the concept of the slice() method in javascript. Good Luck !!!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top