String.slice()
The JavaScript String.slice() method allows you to extract part of a string and return a new string with the extracted value.
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])
beginIndexis where thestringwill be sliced.endIndex(optional) is where the slice will stop. If noendIndexis given, the slice will extract to the length of the string.
NOTE: IfendIndexis 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.
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