JavaScript Slice

The JavaScript Slice function extracts the part of a string and return in a new string. JavaScript Slice function accepts two values. The first is the index position from where the slicing starts, and the second value is the index position where the slicing ends.

Slicing of JavaScript Slice function will go up to the second integer value. Still, it will not include the value at this index position. For instance, if we specify Str_Object(1, 4), then slicing will start at index position one and ends at index position 3 (not 4).

JavaScript Slice String Syntax

The syntax of the String slice function in JavaScript is

String_Object.slice(Start, End)
  • Start: Index position where the slicing will start. If you omit the first index, Slicing will start from the beginning.
  • End: Index position where the JavaScript Slice function slicing ends. If you omit this, string slicing continue to the last or string end.

NOTE: If you are using the Negative Index numbers, string slice function starts slicing from right to left.

JavaScript Slice Method Example

This example will help you understand the slice string method in Js programming language.

<!DOCTYPE html>
<html>
<head>
    <title> Slice JavaScript </title>
</head>
<body>
    <h1> JavaScript Slice </h1>
<script>
    var Str1 = "Tutorial Gateway";
    var Str2 = Str1.slice(2, 13);
    var Str3 = Str1.slice(0, 13);
    var Str4 = Str1.slice(2);
    var Str5 = Str1.slice(2, -3);
    var Str6 = Str1.slice(-3);
 
    document.write(Str2 + "<br \>");
    document.write(Str3 + "<br \>");
    document.write(Str4 + "<br \>");
    document.write(Str5 + "<br \>");
    document.write(Str6 + "<br \>");
</script>
</body>
</html>
JavaScript SLICE Function

It slice the original string, starting at index position 2 and ends at index position 12

var Str2 = Str1.slice(2, 13);

Next, we omitted the second argument, which means JavaScript slice function will start at index value 2 and ends when it reaches last. 

var Str4 = Str1.slice(2);

We used JavaScript negative indexing. So, js starts slicing from -3 (index position of 3 from right to left) and ends at last position. If you use the Negative Index numbers, JS Slice String Function starts looking from right to left (Here, -1 is the Last Item, -2 is Last but one etc)

var Str6 = Str1.slice(-3);