String.slice()

The JavaScript String.slice() method allows you to extract part of a string and return a new string with the extracted value.

String.slice()

The String.slice() method is a way to extract part of a string and return it as a new string while leaving the original unchanged.

Syntax

str.slice(beginIndex[, endIndex])
  • beginIndex is where the string will be sliced.
  • endIndex (optional) is where the slice will stop. If no endIndex is given, the slice will extract to the length of the string.
    NOTE: If endIndex is specified the string will be sliced up until the specified index, but not including it.

Slicing a String

var str = "Welcome to Code Snippet."

str.slice(11, -1)
// returns "Code Snippet"

NOTE: Notice that the .slice() method also works with a negative index.
In this case, using -1 as the endIndex removed the . from the end of the string.
Try this the code snippet in your browser console.

Shoot me an email at [email protected] with any questions and if you enjoyed this, stay tuned and subscribe below! 👇

Help us improve our content