- First character in string javascript
- # Get the first Character of a String in JavaScript
- # Get the first Character of a String using bracket notation
- # Get the first Character of a String using String.at()
- # Get the first Character of a String using String.slice()
- # Get the first Character of a String using String.substring()
- # Get the first Character of a String using Array.from()
- # Additional Resources
- How to Get the First Character of a String
- The charAt() Method
- The substring() Method
- The slice() Method
- The bracket notation [] Method
- String Methods
- Related Resources
- How to Get First Character From a String in JavaScript
- How to Get the First Character From a String in JavaScript?
- Method 1: Get First Character From a String Using Bracket Notation ([ ])
- Method 2: Get the First Character From a String Using charAt() Method
- Method 3: Get First Character From a String Using substring() Method
- Conclusion
- About the author
- Farah Batool
First character in string javascript
Last updated: Jan 2, 2023
Reading time · 4 min
# Get the first Character of a String in JavaScript
To get the first character of a string, call the String.charAt() method with an index of 0 .
The method will return a new string that only contains the first character of the original string.
Copied!const str = 'bobbyhadz.com'; const firstChar = str.charAt(0); console.log(firstChar); // 👉️ b
The String.charAt method returns the character at the specified index.
If the index doesn’t exist in the string, the method returns an empty string.
Copied!console.log('abc'.charAt(0)); // 👉️ a console.log(''.charAt(0)); // 👉️ ""
JavaScript indexes are zero-based. The first character in the string has an index of 0 and the last character has an index of str.length — 1 .
If you call the String.charAt() method with an index that doesn’t exist, it returns an empty string.
Copied!const str = ''; const firstChar = str.charAt(0); console.log(firstChar); // 👉️ ""
# Get the first Character of a String using bracket notation
An alternative approach is to directly access the index.
Accessing the string at index 0 returns the first character of the string.
Copied!const str = 'bobbyhadz.com'; const firstChar = str[0]; console.log(firstChar); // 👉️ b console.log('abcd'[0]); // 👉️ a
If we 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, undefined is returned.
Copied!const str = ''; const first = str[0]; console.log(first); // 👉️ undefined
This is the reason I prefer using the String.charAt() method.
I’d rather get an empty string than an undefined value if I access a string at an index that doesn’t exist.
# Get the first Character of a String using String.at()
The String.at() method returns a new string containing the character at the specified index.
Copied!const str = 'bobbyhadz.com'; const firstChar = str.at(0); console.log(firstChar); // 👉️ b console.log('abcd'.at(0)); // 👉️ a console.log(''.at(0)); // 👉️ undefined
The String.at method takes an integer and returns a new string containing the character at the specified position.
The String.at method allows for positive and negative integers.
You can use negative integers to count back from the end of the string.
Copied!const str = 'bobbyhadz.com'; const firstChar = str.at(0); console.log(firstChar); // 👉️ b console.log(str.at(-1)); // 👉️ m console.log(str.at(-2)); // 👉️ o console.log(str.at(-3)); // 👉️ c
The String.at() method is quite convenient when you need to count backward.
The String.charAt() method and bracket notation approach don’t support negative indexing.
Copied!console.log(str.at(-1)); // 👉️ m console.log(str.charAt(-1)); // 👉️ "" console.log(str[-1]); // 👉️ undefined
You can also use the String.slice() method to get the first character of a string.
# Get the first Character of a String using String.slice()
Specify a start index of 0 and a stop index of 1 to get the first character of a string using the slice() method.
Copied!const str = 'bobbyhadz.com'; const firstChar = str.slice(0, 1); console.log(firstChar); // 👉️ b
The String.slice method extracts a section of a string and returns it, without modifying the original string.
The String.slice() method takes the following arguments:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.
The stop index is exclusive (up to, but not including), so the second character is not contained in the result.
If you try to get the first character of an empty string using slice() , an empty string is returned.
Copied!console.dir(''.slice(0, 1)); // 👉️ ''
# Get the first Character of a String using String.substring()
You can also use the String.substring() method in a similar way.
Copied!const str = 'bobbyhadz.com'; const firstChar = str.substring(0, 1); console.log(firstChar); // 👉️ b
The String.substring() method returns a slice of the string from the start index to the excluding end index.
The method takes the following parameters:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
If no end index is specified the slice goes to the end of the string.
If you try to get the first character of an empty string using substring() , an empty string is returned.
Copied!console.dir(''.substring(0, 1)); // 👉️ ''
The substring() and slice() method seem identical from the previous 2 code samples.
However, there are a couple of differences between the String.substring() and the String.slice() methods:
- The substring() method swaps its start and end index if the start index is greater than the end index. The slice() method returns an empty string in this case.
Copied!const str = 'bobby'; console.log(str.substring(3, 0)); // 👉️ bob console.log(str.slice(3, 0)); // 👉️ ''
- If either of both arguments passed to substring() are negative, they are treated as if they were 0 .
Copied!const str = 'bobby'; console.log(str.substring(-3)); // 👉️ bobby console.log(str.slice(-3)); // 👉️ bby
When given a negative index, the slice() method counts backward from the end of the string to find the indexes.
# Get the first Character of a String using Array.from()
When working with Unicode strings that might contain emojis or other special characters, you might have to convert the string to an array of characters using Array.from() .
Copied!const str = '🐴bobbyhadz.com'; const firstChar = Array.from(str)[0]; console.log(firstChar); // '🐴'
The Array.from() method converts the supplied iterable to an array.
Copied!const str = '🐴bobbyhadz.com'; // [ // '🐴', 'b', 'o', 'b', // 'b', 'y', 'h', 'a', // 'd', 'z', '.', 'c', // 'o', 'm' // ] console.log(Array.from(str));
The last step is to access the character at index 0 .
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
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
The substring() Method
You can also use the substring() method to get the first character:
Javascript substring method
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
And to get the last character, you can simply use:
Javascript slice method
The bracket notation [] Method
There is [] bracket 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
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.
Related Resources
- How to Check If a String Contains Another Substring in JavaScript
- How to Check Whether a String Matches a RegEx in JavaScript
- How to Encode and Decode Strings with Base64 in JavaScript
- How to Convert JavaScript String to be All Lowercase and Vice Versa
- How to Replace All Occurrences of a String in JavaScript
- How to Get the First Key Name of a JavaScript Object
- How to Convert String to Number in JavaScript
- How to Get Query String Values in JavaScript
- How to Get the Last Characters of a String
- How to Get the Last Item in an Array
- How to Convert Object to String
- JavaScript Data Types
- JavaScript Strings
How to Get First Character From a String in JavaScript
During website development, developers need to get the string characters. Sometimes, it is required to access the first or last character or a substring of a string. Here, the string’s first character is required. To do so, the JavaScript predefined methods are used, including the Bracket Notation ([ ]), charAt() method, or the substring() method.
This article will demonstrate the methods for getting the first letter of a string in JavaScript.
How to Get the First Character From a String in JavaScript?
To get the string’s first character, utilize the following methods:
Let’s see how the above methods work.
Method 1: Get First Character From a String Using Bracket Notation ([ ])
In JavaScript, bracket notation ([ ]) is the basic approach for getting the first character from a string. To do so, pass the “0” index.
Use the given syntax for getting the first character from a string using the bracket notation:
Here, “0” is the index of the string for getting the first letter of the string.
First, creates a string and store it in a variable “string”:
Get the first character of a string using the bracket notation ([ ]) by passing the index of the first character that is “0” and store it in a variable “firstChar”:
Print the first letter of the string on the console using the “console.log()” method:
The output displays “W”, which is the first character of the string:
Let’s see the second method to get the first character of the string.
Method 2: Get the First Character From a String Using charAt() Method
For getting the string’s first character, use the “charAt()” method. It gives the character as an output in a string at a particular position called index. For the first character, pass the “0” index as a parameter in the charAt() method.
Follow the given syntax for the charAt() method:
Here, pass the index “0” for the first element of the string.
Call the charAt() method by passing 1st index of the string with the created string and storing the result in a variable “firstChar”:
The corresponding output shows that “W” is the string’s first character:
Method 3: Get First Character From a String Using substring() Method
Another method for getting the string’s first letter is the “substring()” method. It extracts characters from start to end between two indexes and returns the substring.
The following syntax is used for the substring() method:
Call the “substring()” method by passing two indexes, “0”, the first index of the string, and “1”, which is the second index of the string, as parameters. It will split the string between these indices:
The output indicates that the first letter is successfully retrieved using the substring() method.
All the relevant information is compiled to get the first letter of the string.
Conclusion
To get the first character from a string, use the JavaScript pre-built methods, including the Bracket Notation ([ ]), charAt() method, or the substring() method. All these ways successfully retrieve the first letter of the string. This article demonstrated the methods for getting the first character from a string in JavaScript with examples.
About the author
Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.