3 examples to use Javascript slice method

The slice method of Javascript

The slice method of strings in Javascript is used to extract the substring from a given string by specifying start and end positions. The start and end positions are index numbers that can be positive or negative values.

Following are a few examples of using JS slice function but let us first look at its syntax.

See an example of Slice method

Syntax of slice method

Following is the syntax to use slice javascript method:

Str.slice(start_index, end_index);

A few points about slice method are:

  • The start_index specifies where to start extracting substring.
  • The End_index specifies where to end extracting the substring.
  • You can use positive or negative numbers in the start and end indices.
  • If a negative value is given then it will start counting from the end of given string.
  • The original string remains the same after using the slice function.

e.g. str_slice = str.slice(5,10);

Let us look at a few examples of using javascript string slice.

Tip: The array slice function is different to string slice. Learn how to use array slice method.

Javascript slice string with start and end indices example

In the following example, we will use both parameters in the slice method. We will specify the start and end index and the sliced string will be shown in an alert. See example by clicking the link below:

Experience this example online


As you click on the button “Show Slice” it will show sliced string “javascript string” in an alert.

A slice string example with start index only

In this example, we will only specify start index in slice method. No end index is given and it should return remaining string. See example online by clicking the link below:

Experience this example online


You can see, from the eighth character (begin index) the string is sliced to end as no end index is given. The result string is “javascript string tutorial!”.

A string slice with negative start and end index example

As mentioned earlier,  if negative numbers are specified in start and end index, it will be counted from the end of strings. Following example uses negative start and end index numbers in javascript slice method. The extracted string is then shown in an alert.

Experience this example online


As you can see, we specified two slice method arguments with -16 for start and -1 for end index. It returned “string tutorial” after using slice method.

Also see Javascript String | Javascript substring

Was this article helpful?

Related Articles

Leave A Comment?