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
- 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.
- 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
let str = 'Leo Messi';
let result = str.slice(4);
console.log(result);
Output
Messi
Example 2: 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 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
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Thanks, your article helped me finish a job! ;D