Get the First 3 Characters of a String in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 24 20212 min read

banner

Photo by Luke Dahlgren

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
Indexes are zero-based in JavaScript, which means that the first index in a string is 0 and the last is str.length - 1.

To get the index of 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.

To get the first three characters of a string, call the slice() method, passing it 0 as the first parameter and 3 as the second. The 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 as we did with the substring method, 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 for other use cases. If you want to read more on that, check out the section in the MDN docs.

My personal preference is the String.slice method because it's shorter, easier to read and more intuitive than String.substring for other use cases mentioned in the MDN docs.

Further Reading #

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