
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.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer
