Menu Home

String.charAt()

Hi everyone, and welcome to another sleeper of a Boring JavaScript episode! Today, we tackle the String.charAt() method. Hold on to your hats – this is going to be a short one.

Don’t like to read? Then watch our video.

So Where Is That Character?

The String.charAt() method simply finds the character inside of a string, given an index. For example:

const myCat = "Fluffy";
const thirdCharacter = myCat.charAt(2);
console.log(`The third character in my cat's name is "${thirdCharacter}".`);

/* output
The third character in my cat's name is "u".
*/

The string “Fluffy” has six characters in it, indexed 0 through 5. To get the third character, we pass in the index number of the character we wish – in the above example that would be “2” for the third character.

And that’s it! But wait … what if the number is out of bounds? Let’s look at that:

console.log(`-1 = "${myCat.charAt(-1)}".`);
console.log(`1000 = "${myCat.charAt(1000)}".`);

/* output
-1 = "".
1000 = "".
*/

If the index number happens to be out of range, charAt() will return an empty string.

And if the index number happens to be a String, it will convert that string into a number before performing the operation:

console.log(`String 2 = "${myCat.charAt("2")}".`);

/* output
String 2 = "u".
*/

And that’s pretty much it!

The Video

Here is the video we did on the subject:

Shameless Plug

Check us out all over the Internet World!

Check out all our videos at: https://www.boringjavascript.com

Check out everything at: https://www.thevirtuoid.com

Facebook: https://www.facebook.com/TheVirtuoid

Twitter: https://twitter.com/TheVirtuoid

YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: