Get the First 2 Characters of a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the First 2 Characters of a String #

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

index.js
const str = 'Cook dinner'; const first2 = str.slice(0, 2); console.log(first2); // 👉️ Co

We passed the following parameters to the String.slice method:

  1. start index - the index of the first character to be included in the new string
  2. end index - extract characters up to, but not including this index
JavaScript indexes are zero-based, so the first index in a string is 0 and the last is str.length - 1.

We specified a start index of 0 and an end index of 2, meaning extract characters in positions 0 and 1.

The slice method doesn't change the original string, it returns a new string. Strings are immutable in JavaScript.

An alternative, but also very common approach is to use the String.substring method.

Use the String.substring() method to get the first two characters of a string, e.g. const first2 = str.substring(0, 2);. The substring method will return a new string containing the first two characters of the original string.

index.js
const str = 'Cook dinner'; const first2 = str.substring(0, 2); console.log(first2); // 👉️ Co

We passed the same parameters to the substring method as we did with the slice method - the start and end indexes.

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

My personal preference is the String.slice method because its default behavior is more intuitive than String.substring 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.