Tue Oct 05 2021·1 min read
Photo by Aldino Hartan Putra
To get the first N characters of a string, call the
slice method on the
string, passing in
0 as the first parameter and the number of characters to
get as the second, e.g.
str.slice(0, 3) returns a new string with the first 3
characters 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 pass to the
String.slice method is the
start index - the index at which we begin extraction of characters.
The second parameter is the
end index - extract characters up to this index,
but not including.
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);
In the example we try to get the first
100 characters of a string, which only
11 characters. As a result the
slice method returns the whole
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 the
I'll send you 1 email a week with links to all of the articles I've written that week