How to get first character of a string in JavaScript?

Working with strings is a common task in JavaScript, and sometimes you may need to extract the first character of a string to perform a specific operation. In this post, we will explore different ways to get the first character of a string in JavaScript, with the pros and cons of each approach and examples to help you choose the most appropriate method for you.

How to get first character of a string in JavaScript?

To do this you can use one of three native JavaScript methods built-in to the String prototype – charAt, substring, or slice. The first one returns a character with the specific index, and the two next returns part of the string between the provided start index and the end index (it is worth noticing that index in JavaScript starts at 0).

Generally, there is no difference between them, so you can choose the one you prefer.

const string = "Hello there!";

string.substring(0, 1);
string.slice(0, 1);

// The result of each above method will be "H" letter

How to deal with Unicode characters?

Despite the above methods are great there is one edge case where they can fail – when the first character of the string is encoded with Unicode 😱.

In simple worlds, in JavaScipt each Unicode character takes place of two characters, so all above methods return a half part of the Unicode character, and this gives us the incorrect result. To get the first character of a Unicode string, you can use a combination of Array.from method and reference to the index.

Array.from('😎 <- this is Unicode character')[0];

How to get last character of a string in JavaScript?

In the case to get the last character of a string, you can use each of the above solutions, but you need to change appropriate indexes. To use charAt method or Array.from approach, you need to change index of the first character (which is 0 in JS) to the index of the last character (which is the length of the string minus 1).

const string = "Hello there!";

string.charAt(string.length - 1);

To use substring and slice methods you need to update both parameters like in the example below.

const string = "Hello there!";

string.substring(string.length - 1, string.length);
string.slice(string.length - 1, string.length);

Now, you are able to get the first and the last characters of a string in JavaScript with the pros and cons of each approach.

Leave a Reply

Your email address will not be published. Required fields are marked *