Get the first N characters of a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the first N characters of a String #

Use the String.slice() method to get the first N characters of a string, e.g. 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.

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 doesn't mutate the original string, it returns a new string. Strings are immutable in JavaScript.

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 string.

The second parameter is the end index - go up to but not including this character.

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);

We tried to get the first 100 characters of a string that only contains 11 characters. As a result, the slice method returned the whole string.

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 this section of the MDN docs.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.