• JavaScript Video Tutorials

JavaScript String slice() Method



The JavaScript String slice() method is used to extract a sub-string from the original string and returns a new string. It does not modify the original string.

It takes two parameters: 'startIndex' and 'endIndex'. It extracts a part of the string from the original string, starting from startIndex and before endIndex. For example, "Hello".slice(2, 4) returns "ll'. It starts extracting from index 2 and extracts up to 3 (exclude index 4).

Syntax

Following is the syntax of JavaScript String slice() method −

slice(indexStart, indexEnd)

Parameters

This method accepts two parameters named 'indexStart' and 'indexEnd', which are described below −

  • indexStart − The starting position of the extracted substring.
  • indexEnd− The ending position of the extracted substring.

Return value

This method returns a new extracted string.

Example 1

If we omit the endIndex parameter, it will start extracting from startIndex up to the end of the string.

In the following program, we are using the JavaScript String slice() method to extract a part of a string from the original string "TutorialsPoint" at startIndex 5 up to the end.

<html>
<head>
<title>JavaScript String slice() Method</title>
</head>
<body>
<script>
   const str = "TutorialsPoint";
   document.write("Original string: ", str);
   let startIndex = 5;
   const extracted_str = str.slice(startIndex);
   document.write("<br>Extracted string: ", extracted_str);
</script>    
</body>
</html>

Output

The above program returns a new string "".

Original string: TutorialsPoint
Extracted string: ialsPoint

Example 2

If we pass the both startIndex and endIndex parameters to this method, it starts extracting a part of the string at startIndex and extracts up to endIndex(excluding).

The following is another example of the JavaScript String slice() method. In this example, we are using this method to extract a part of the string from the original string "Hello World" at starting position 7 up to end position 11.

<html>
<head>
<title>JavaScript String slice() Method</title>
</head>
<body>
<script>
   const str = "Hello World";
   document.write("Original string: ", str);
   let startIndex = 6;
   let endIndex = 11;
   document.write("<br>StartIndex = ", startIndex, " and EndIndex = ", endIndex);
   const extracted_str = str.slice(startIndex, endIndex);
   document.write("<br>Extracted string: ", extracted_str);
</script>    
</body>
</html>

Output

After executing the above program, it returns a new string as "World".

Original string: Hello World
StartIndex = 6 and EndIndex = 11
Extracted string: World
Advertisements