JavaScript String slice() Method

JavaScript String slice() method is used to extract a part of a string and return it as a substring. It does not modify the original string.

This method accepts negative indices, unlike the substring() method, which does not support negative indices.

Syntax

string.slice(startIndex, endIndex)

Parameters

  1. startIndex(required): It is the position where to begin the extraction. The first character is at position 0. We can use the negative values to specify the position from the end of the string.
  2. endIndex(optional): It is the position (up to, but not including) where to end the extraction.

Return value

Returns a new string containing the extracted part of the string.

Example 1: How to Use the String slice() Method

Visual Representation of JavaScript String slice() Method

let str = 'Leo Messi'; 
let result = str.slice(4); 
console.log(result);

Output

Messi

Example 2: Using the endIndex parameterVisual Representation of Using the endIndex parameter

let str = 'Leo Messi'; 

console.log(str.slice(0,3)); 
console.log(str.slice(5,8));

Output

Leo
ess

Example 3: Using negative indicesVisual Representation of Using negative indices

If startIndex or endIndex are negative, the values are counted from the end of the string(backward).

let str = 'Leo Messi'; 
let result = str.slice(-5); 
console.log(result);

console.log(str.slice(-9,-6));
console.log(str.slice(-5,-1)); 

Output

Messi
Leo
Mess

Browser compatibility

  • Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Opera 4 and above
  • Safari 1 and above

1 thought on “JavaScript String slice() Method”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.