How to Get the First Character of a String in JavaScript?

How can I javascript get the first character of a string? I have a string, and I need to retrieve its first character. How can I fix my code?

Sure thing! If you want to javascript get first character of string, using bracket notation is a simple way to do it. Here’s an example:


var str = "Hello";

var firstChar = str[0];

console.log(firstChar); // Output: H

This method directly grabs the character at index 0, giving you the first character of any string.

Another good approach is using the charAt() method, which is handy for string manipulation in JavaScript. If you want to javascript get first character of string, here’s how charAt() works:


var str = "Hello";

var firstChar = str.charAt(0);

console.log(firstChar); // Output: H

The charAt() method is reliable because it’s compatible with older JavaScript versions, so it’s great for broader support.

You could also go with the slice() method, especially if you’re already familiar with slicing strings in JavaScript. To javascript get first character of string, you can slice the string from the start index up to the first character like this:


var str = "Hello";

var firstChar = str.slice(0, 1);

console.log(firstChar); // Output: H

slice() is quite flexible, allowing you to modify the range and extract multiple characters if needed.