JavaScript slice() Method
This tutorial introduces the slice() method, from the JavaScript String object. The slice() method slices a string into substrings, whose length depends on integers passed as argument. The slice() method does not modify the original string: instead, it returns a string copy of the result.
This tutorial explains the String slice() method. Are you looking for the Array slice() method?
Using the slice() Method with One Argument
The slice() method takes at least one integer argument, which determines after which character the substring will be extracted.
var carter = new String("I learn JavaScript.");
alert( carter.slice(7) );
Our script extracts a substring starting at index 7 (8th character) of our original string. Since no second argument was passed to limit our substring, the slice() method included every character after the eighth.
The slice() method accepts a negative first argument. In that case, the substring's start is counted leftwards (from end to start, several times if the argument is greater than the length of the string).
Passing a Negative Argument to the slice() Method
Passing a negative integer as argument to the slice() method is perfectly valid: slice() will cycle backwards (from end to start) through the string until it has iterated through as many characters as the absolute value of the integer passed (five characters leftwards, if -5 is passed).
var carter = new String("I learn JavaScript.");
alert( carter.slice(-7) );
The slice() method iterated through 7 characters leftwards, and returned the substring below. (In this case, since 7 was less than the length of the string, it returned the last seven characters of our original string.)
Using the slice() Method with Two Arguments
The second argument optionally accepted by the slice() method is also an integer, and determines the length of the substring returned.
var carter = new String("I learn JavaScript.");
alert( carter.slice(8, 12) );
The slice() method returned the substring starting at position index 8, ending at position index 12 (a substring of length 4).
Passing Two Negative Arguments to the slice() Method
Like the first, the second argument can be negative, in which case the string is extracted leftwards, rather than from left to right. In the script below, the slice() method starts a substring 7 characters from the end, and ensures a length of 4 with the second argument we supply.
var carter = new String("I learn JavaScript.");
alert( carter.slice(-11,-7) ); // Same as carter.slice(8,-7)
Our script returns the substring starting 11 characters from the end, and ending 7 characters from the end of our original string:
Test the slice() Method
Interactively test the slice() method by editing the JavaScript code below and clicking the Test slice() Method button.
Browser support for JavaScript slice() method | |||
---|---|---|---|