How to Get the First Character of a String
Read this JavaScript tutorial and learn several string methods that are used to retrieve the first character of a string. Choose the best one for you.
There are multiple methods of getting the first character of a string in JavaScript. Here are some easy methods presented below.
The charAt() Method
You should use the <kbd class="highlighted">charAt()</kbd> method at index 0 for selecting the first character of the string.
Javascript charAt method
The substring() Method
You can also use the substring() method to get the first character:
Javascript substring method
Avoid using the <kbd class="highlighted">substr()</kbd> method as it is considered a legacy function. Do not use it in your code as it is not a part of JavaScript and can be removed at any time. Use the <kbd class="highlighted">substring()</kbd> method, instead.
The slice() Method
However, if prefer to use substring, the slice() version is shorter:
Javascript slice method
And to get the last character, you can simply use:
Javascript slice method
The bracket notation [] Method
There is <kbd class="highlighted">[] bracket</kbd> notation method of rethrieving the first element:
Javascript [] bracket notation method
Unlike all above mentioned methods that return an empty string ('') for str = '' this method returns undefined:
Javascript empty string methods
String Methods
There are 3 methods used to extract a part of a string:
- slice(start, end) - extracts a part of a string and returns the extracted part in a new string.
- substring(start, end) - similar to
<kbd class="highlighted">slice()</kbd>only it cannot accept negative indexes. - substr() -
<kbd class="highlighted">substr()</kbd>is similar to<kbd class="highlighted">slice()</kbd>except the second parameter specifies the length of the extracted part.
There are 2 methods of accessing an individual character in a string:
- charAt() - returns the character at a specified index (position) in a string.
- bracket notation [] - treas the string as an array-like object, where each individual character corresponds to a numerical index.