Last updated: Jul 25, 2022
Photo from Unsplash
String.slice() method to get the first N characters of a string,
str.slice(0, 3). The
slice() method takes the start and stop indexes as
parameters and returns a new string containing a slice of the original string.
const str = 'Hello World'; const first3 = str.slice(0, 3); // 👉️ Hel console.log(first3); const first2 = str.slice(0, 2); // 👉️ He console.log(first2);
The first parameter we passed to the
String.slice method is the
start index - the index of the first character to be included in the new
The second parameter is the
end index - go up to but not including this
end indexyou provide to the
String.slicemethod is greater than the string's length, the method does not throw an error, instead it returns a copy of the entire string.
const str = 'Hello World'; const first100 = str.slice(0, 100); // 👉️ Hello World console.log(first100);
We tried to get the first
100 characters of a string that only contains
characters. As a result, the
slice method returned the whole string.
String.substringmethod can also be used to get the first
Ncharacters of a string, however
String.sliceis more flexible and intuitive to use.
If you want to read about the difference between
String.slice, check out
of the MDN docs.