In this post you will learned how to get the First and Last Characters of a String in JavaScript;
In Javascript to get the first and last characters of a string, you can use the charAt() method.
const str = 'hello';
const first = str.charAt(0);
console.log(first); // h
const last = str.charAt(str.length - 1);
console.log(last); // o
Indexes are zero-based in JavaScript. The first character in the string has an index of 0
and the last has an index of str.length - 1
.
If you pass an index that doesn’t exist in the string, the charAt
method returns an empty string.
const str = '';
const first = str.charAt(0);
console.log(first); // ""
const last = str.charAt(str.length - 1);
console.log(last); // ""
To get the first and last characters of a string, access the string at the first and last indexes. For example, str[0] returns the first character, whereas str[str.length – 1] returns the last character of the string.
const str = 'hello';
const first = str[0];
console.log(first); // h
const last = str[str.length - 1];
console.log(last); // o
If we just access the string at the specific index we can avoid calling the charAt
method.
However, if you try to access the string at an index that doesn’t exist you get undefined
back.
const str = '';
const first = str[0];
console.log(first); // undefined
const last = str[str.length - 1];
console.log(last); // undefined