Get the First 2 Characters of a String in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 24 20212 min read

banner

Photo by Amy Tran

Get the First 2 Characters of a String #

To get the first two characters of a string, call the slice() method, passing it 0 and 2 as parameters. The 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 (zero-based) at which we start extraction
  2. end index - extract characters 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.

For our use case, we specified a start index of 0 and an end index of 2, meaning extract characters in positions 0 and 1.

The slice method does not 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.

To get the first two characters of a string, call the substring() method passing it 0 as the first parameter and 2 as the second. The 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 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