Get the First 3 Characters of a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the First 3 Characters of a String #

To get the first three characters of a string, call the substring() method and pass it 0 and 3 as parameters. The substring method will return a new string containing the first three characters of the original string.

index.js
const str = 'Walk the dog'; const first3 = str.substring(0, 3); console.log(first3); // 👉️ Wal

The two parameters we passed to the String.substring method are:

  1. the start index - the index of the first character to be included in the returned string
  2. the end index - go up to, but not including this index
JavaScript indexes are zero-based. The first character in a string has an index of 0 and the last an index of str.length - 1.

To get the first three characters, we specified a start index of 0 and an end index of 3. This extracts characters at positions: 0, 1 and 2.

An alternative approach is to use the String.slice method.

Use the string.slice() method to get the first three characters of a string, e.g. const first3 = str.slice(0, 3);. The slice method will return a new string containing the first three characters of the original string.

index.js
const str = 'Walk the dog'; const first3 = str.slice(0, 3); console.log(first3); // 👉️ Wal

We passed the same parameters to the slice method - the start and end indexes. However, the methods are not identical.

For our purposes, the slice and substring methods do the same. However, there are some differences between the two.

If you want to read more on that, check out this section in the MDN docs.

Which approach you pick is a matter of personal preference. I'd go with the String.slice method as I find it more intuitive for other use cases mentioned in 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.