Start learning free

LESSON 63 OF 675 · STRINGS I

Accessing characters in TypeScript

Lesson

Each character in a string has a numbered position known as its index. We access a character by referring to its index number.

Strings use zero-based indexing, so the first character in a string has an index of 0, the second character has an index of 1, etc.

We’re using bracket notation ([]) with the index after the name of the string to access the character:

let message = "Hello world!";

console.log(message[0]); // Output: H
console.log(message[1]); // Output: e
console.log(message[6]); // Output: w

Whitespaces have indices:

Note that every character inside the quotes (including whitespaces) is part of the string and has its own index. For example, in string "Hello world!", the whitespace is placed on index 5.

However, if you run this code:

let message = "Hello world!";

console.log(message[5]);

you would see what looks like an empty line in the console.

This is because console.log() did print the whitespace, followed by its usual new line, but a space is invisible on screen.

But don't get tricked by this, that whitespace exists and it's on index 5. You can see that clearly when you run this code:

let message = "Hello world!";

console.log(message[4] + message[5] + message[6]);

the output is:

o w

Assignment
Follow the Coding Tutorial and let's access some characters!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check