Press ESC to close

JavaScript charAt

0 2110

The JavaScript charAt method used on strings returns one character from a string. The position of the character is indicated in the index between round brackets.

So for example charAt (0) returns the first character, while charAt (1) returns the second and so on.

The syntax is therefore the following: string.charAt(index)

Therefore the method accepts a mandatory parameter, index, which represents the position of the character to search for in a string.

JavaScript charAt – examples

In this first example we will search for the first character of a string in a simple sentence.

Here is a possible implementation:



var sentence = 'do coding creativo';
var character = sentence.charAt(0);
console.log(character);

In this case, the result is the letter f (the first letter of the sentence).

If, on the other hand, we look for a position in the sentence that does not exist, we will not get any value, as in the example below:



var sentence = 'do coding creativo';
var character = sentence.charAt(200);
console.log(character);

Last character of a string using the JavaScript charAt method

If we want to determine the last character of a string, then we can use the length property on the string. In fact, remember that str.length returns the amount of characters in a string, so to get the last character, since the index starts from 0, we must subtract 1.

Here is the complete example:



var sentence = 'do coding creativo';
var character = sentence.charAt(sentence.length-1);
console.log(character);

Capitalize the first character with the JavaScript charAt and uppercase method

In this exercise we extract the first character, convert it to uppercase with the toUpperCase method and then concatenate everything else using the substr method.

Here is the complete example:



var sentence = 'do coding creativo';
var sentenceUpper = sentence.charAt(0).toUpperCase() + sentence.substr(1);
console.log(sentenceUpper);

In this short lesson we have implemented some very simple exercises using the JavaScript charAt method, continuing in the tutorial you will find many other application examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants

Other stories

JavaScript charCodeAt

Next Story

JavaScript search

Previous Story