substring. We start by describing and demonstrating the
slice method since it is more flexible than the
slice method on a string, a new string is returned consisting of a segment of the original string as determined by the arguments you pass to the
slice method. The first argument specifies the index location at which to start the selection in the string. The second argument is optional; it specifies the index location at which to end the selection. If the end argument is not included, the selected segment continues to the end of the string, as we demonstrate here:
var str = 'unbelievable'; // pass (zero-based) index location to slice var str2 = str.slice(2); console.log(str2); // believable
slice method returns a segment of the string it is invoked on and does not modify the original string. So we assign the returned value to a new string in our examples.
The substring returned by
slice does not include the character at the index location of the end argument, as we show here:
var str = 'unbelievable'; var str3 = str.slice(2, 4); console.log(str3); // be
As you can see in the example above, the substring returned by
slice includes the character specified by the first argument, but not that specified by the second argument.
Passing Negative Index Values to the slice Method
Both arguments to the
slice method can be negative integers, in which case they specify the number of characters from the end of the string at which to start or end the substring selection. The following example starts the substring selection four characters from the end of the string by passing
-4 to the
var str = 'unbelievable'; var str4 = str.slice(-4); console.log(str4); // able
The next example passes
-2 to the
slice method to start substring selection four characters from the end of the string, and end substring selection two characters from the end of the string:
var str = 'unbelievable'; var str5 = str.slice(-4, -2); console.log(str5); // ab
The substring Method
substring method is similar to
slice in that you specify start and end index locations for selecting a segment from the original string. But unlike
slice, you can't specify the locations using negative integers.
The following shows how to use the
substring method to accomplish the same results that were demonstrated above using
var str = 'unbelievable'; var str2 = str.substring(2); console.log( str2 ); // believable var str3 = str.substring(2, 4); console.log( str3 ); // be // use str.length to specify location from end of string var str4 = str.substring( str.length -4 ); console.log( str4 ); // able var str5 = str.substring( str.length -4, str.length -2 ); console.log( str5 ); // ab
Although we are at able to achieve the same results with the
substring method as with
slice, it is rather awkward if you want to specify the location from the end of the string since the method does not support negative integer arguments.