The slice() method extracts a section of a string and returns a new string.
str.slice(beginSlice[, endSlice])
beginSlicesourceLength + beginSlice where sourceLength is the length of the string (for example, if beginSlice is -3 it is treated as sourceLength - 3).endSliceslice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3).slice() extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.
slice() extracts up to but not including endSlice. str.slice(1, 4) extracts the second character through the fourth character (characters indexed 1, 2, and 3).
As an example, str.slice(2, -1) extracts the third character through the second to last character in the string.
slice() to create a new stringThe following example uses slice() to create a new string.
var str1 = 'The morning is upon us.'; var str2 = str1.slice(4, -2); console.log(str2); // OUTPUT: morning is upon u
slice() with negative indexesThe following example uses slice() with negative indexes.
var str = 'The morning is upon us.'; str.slice(-3); // returns 'us.' str.slice(-3, -1); // returns 'us' str.slice(0, -1); // returns 'The morning is upon us'
Created by Mozilla Contributors and licensed under CC-BY-SA 2.5