Extracting String Parts: Slice() Method

The first of three methods for extracting a part of a string is the slice(start, end) method which extracts a part of a string and returns the extracted part in a new string. This method takes 2 parameters: the starting index (position), and the ending index (position). In this example, a portion of a string from position 7 to position 13 is sliced out:

   var str = "Apple, Banana, Kiwi";
   var res = str.slice(7,13);

HTML file: Displayed by browser:
<body>
<p>The slice() method extract a part of a string
and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
    var str = "Apple, Banana, Kiwi";
    document.getElementById("demo").innerHTML = str.slice(7,13);
</script>
</body>

The slice() method extract a part of a string and returns the extracted parts in a new string:

If a parameter is negative, the position is counted from the end of the string. This example slices out a portion of a string from position -12 to position -6:
     var res = str.slice(-12,-6);    The result of res will be Banana

If you omit the second parameter, the method will slice out the rest of the string:
     var res = str.slice(7);    The result of res will be Banana, Kiwi

or, counting from the end:
     var res = str.slice(-12);    The result of res will be the string at the location and to the RIGHT of it, which is Banana, Kiwi


Negative positions does not work in Internet Explorer 8 and earlier.

BackTable of ContentsNext