JavaScript slice

The JavaScript slice method extracts the part of a string and returns a new string. The slice function accepts two values. The first is the index position from where it starts, and the second value is the index position where it ends.

Slicing of the text 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 sit will start at index position one and ends at 3 (not 4).

Syntax

The syntax of the JavaScript slice string function is

String_Object.slice(Start, End)
  • Start: Index position where it will begin. If you omit the first one, it will start from the beginning.
  • End: Index position where the function finishes. It will continue to the last or string end if you omit this.

NOTE: If you are using the Negative Index numbers, it starts from right to left.

JavaScript slice method Example

This example will help you understand the string slice method. The variable var str2 cuts the original string, starting at 2 and ending at 12. Next, we omitted the second argument, which means it will begin at 2 and finish when it reaches last.

In var Str6, we used JavaScript negative indexing. So, it starts slicing from -3 (3 from right to left) and ends at the last position. If you use the Negative numbers, this String Function begins looking from right to left (Here, -1 is the Last Item, -2 is Last but one, etc)

<!DOCTYPE html>
<html>
<head>
    <title> SliceJavaScript </title>
</head>
<body>
    <h1> JavaScriptSlice </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