0
0
JavascriptHow-ToBeginner · 3 min read

How to Slice String in JavaScript: Simple Guide

In JavaScript, you can slice a string using the slice() method, which extracts a part of the string and returns it as a new string. You provide the start index and optionally the end index to specify the part you want to extract.
📐

Syntax

The slice() method is called on a string and takes two arguments:

  • start: The index where slicing starts (inclusive).
  • end (optional): The index where slicing ends (exclusive). If omitted, it slices till the end of the string.

Indexes start at 0. Negative indexes count from the end of the string.

javascript
string.slice(start, end)
💻

Example

This example shows how to slice a string from index 2 to 5, and how to slice from index 3 to the end.

javascript
const text = "Hello, world!";
const part1 = text.slice(2, 5);
const part2 = text.slice(3);
console.log(part1);
console.log(part2);
Output
llo lo, world!
⚠️

Common Pitfalls

Common mistakes include:

  • Using slice() with the end index included (it is exclusive).
  • Confusing slice() with substring() which handles negative indexes differently.
  • Not remembering that indexes start at 0.
javascript
const str = "JavaScript";
// Wrong: expecting to include index 4 character
console.log(str.slice(0, 4)); // Outputs 'Java', end index is exclusive

// Right: to include character at index 4, use end index 5
console.log(str.slice(0, 5)); // Outputs 'JavaS'
Output
Java JavaS
📊

Quick Reference

ParameterDescription
startIndex to start slicing (inclusive), can be negative
endIndex to end slicing (exclusive), optional, can be negative

Key Takeaways

Use slice(start, end) to extract parts of a string in JavaScript.
The start index is inclusive, but the end index is exclusive.
Negative indexes count from the end of the string.
If end is omitted, slicing goes to the string's end.
Remember slice() does not change the original string.