0d: 00h: 00m: 00s

🎁 Get 3 extra months of learning β€” completely FREE

That's 90 extra days to master new skills, build more projects, and land your dream job.

Become a PRO
Background Image

🎁 Get 3 extra months of learning completely FREE

Become a PRO
agegnw israeal
PRO
last month
Agegnwcountry asked

What does the slice() method do in JavaScript, and how do I use it with strings?

Abhay Jajodia
Expert
last week
Abhay Jajodia answered

Hello agegnw, really nice question.

In JavaScript, slice() is used to take a part of a string and return it as a new string, without changing the original one.

It works with indexes (positions of characters in the string). JavaScript starts counting from 0.

Basic form:

string.slice(startIndex, endIndex)
  • startIndex β†’ where to start (included)

  • endIndex β†’ where to stop (excluded). If you leave this out, it goes to the end of the string.

Example:

let text = "JavaScript is fun!";

let part1 = text.slice(0, 10);   // from index 0 to 9
console.log(part1);              // "JavaScript"

let part2 = text.slice(11);      // from index 11 to the end
console.log(part2);              // "is fun!"

In the kind of example from your lesson, you might see something like:

let name = "  alice  ";
let trimmed = name.trim();       // "alice"
let result = trimmed[0].toUpperCase() + trimmed.slice(1);
console.log(result);             // "Alice"

Here:

  • trim() removes spaces at the start and end.

  • slice(1) takes the string from index 1 onward ("lice"), so you can rebuild "Alice".

So you can think of it this way:

  • trim() β†’ cleans spaces from the ends.

  • slice() β†’ cuts out the piece of the string you want.

If you have further questions, I'm here to help.

JS
This question was asked as part of the Learn JavaScript Basics course.