Borislav Hadzhiev
Tue Oct 05 2021·2 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 String.slice method does not mutate the original string, it returns a new string. Strings are immutable in JavaScript.
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 index
you provide to the String.slice
method 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
contains 11
characters. As a result the slice
method returns the whole
string.
String.substring
method can also be used to get the first N
characters of a string, however String.slice
is more flexible and intuitive to use.If you want to read about the difference between String.substring
and
String.slice
, check out the
MDN docs.