How to Get the First Character of a String
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 charAt() method at index 0 for selecting the first character of the string.
Javascript charAt method
let string = "w3docs.com";
let firstChar = string.charAt(0); // Returns "w"
console.log(firstChar);
The substring() Method
You can also use the substring() method to get the first character:
Javascript substring method
const x = 'w3docs.com';
console.log(x.substring(0, 1));
Avoid using the substr() 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 substring() method, instead.
The slice() Method
However, if prefer to use substring, the slice() version is shorter:
Javascript slice method
const x = 'w3docs.com';
console.log(x.slice(0, 1));
And to get the last character, you can simply use:
Javascript slice method
const x = 'w3docs.com';
console.log(x.slice(-1));
The bracket notation [] Method
There is [] bracket notation method of rethrieving the first element:
Javascript [] bracket notation method
const string = 'w3docs.com';
console.log(string[0]);
Unlike all above mentioned methods that return an empty string ('') for str = '' this method returns undefined:
Javascript empty string methods
var string = "";
console.log(string.slice(0, 1));
console.log(string.charAt(0));
console.log(string.substring(0, 1));
console.log(string[0]);
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 slice() only it cannot accept negative indexes.
- substr() - substr() is similar to slice() 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.