Generally, there is no difference between them, so you can choose the one you prefer.
const string = "Hello there!"; string.charAt(0); 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');
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);
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);