We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

52
2.169.719,45

Cart

Quantity 8.346,15
Quantity 100,00
Quantity 146.999,00
Quantity 625,00
Quantity 1.300,00
Quantity 5.500,00
Quantity 19.800,00

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,

Advertisements

  • 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 !!!

52
2.169.719,45

Cart

Quantity 8.346,15
Quantity 100,00
Quantity 146.999,00
Quantity 625,00
Quantity 1.300,00
Quantity 5.500,00
Quantity 19.800,00