Get the first N characters of a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 05 20211 min read

Get the first N characters of a String #

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.

index.js
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.

Even if the 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.
index.js
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.

You might know that the 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee