JavaScript slice

The JavaScript slice method 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 it starts, and the second value is the index position where it ends.

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

JavaScript slice String 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 finish. If you omit this, it will continue to the last or string end.

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 ends 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, js starts slicing from -3 (3 from right to left) and ends at last position. If you use the Negative numbers, this String Function begin 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