Javatpoint Logo
Javatpoint Logo

JavaScript String slice() Method

The JavaScript string slice() method is used to fetch the part of the string and returns the new string. It required to specify the index number as the start and end parameters to fetch the part of the string. The index starts from 0.

This method allows us to pass a negative number as an index. In such case, the method starts fetching from the end of the string. It doesn't make any change in the original string.

Syntax

The slice() method is represented by the following syntax:

Parameter

start - It represents the position of the string from where the fetching starts.

end - It is optional. It represents the position up to which the string fetches. In other words, the end parameter is not included.

Return

Part of the string

JavaScript String slice() Method Example

Let's see some simple examples of slice() method.

Example 1

Here, we will print the part of the string by passing starting and ending index.

Test it Now

Output:

vat

Example 2

Here, we will provide starting index only. In such case, the method fetches the string up to its length.

Test it Now

Output:

Javatpoint

Example 3

This is one more example where we provide only the starting index.

Test it Now

Output:

tpoint

Example 4

In this example, we will provide negative number as an index. In such case, the method starts fetching from the end of the string.

Test it Now

Output:

point

Example 5

In this example, we will provide negative number as a starting and ending index. In such case, the method starts fetching from the end of the string.

Test it Now

Output:

poin

Next TopicJavaScript String




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA