Start learning free

LESSON 66 OF 675 · STRINGS I

String Length in TypeScript

Lesson

We can get the length of a string using the .length property like this:

let message = "Hello world";

// Printing the length:
console.log(message.length); // Output: 11

// Changing the message:
message += "!";

// Printing the new length:
console.log(message.length); // Output: 12

Accessing characters from the end:

The length is useful for accessing characters from the end of a string.

Because strings are 0-indexed, the index of the last character is length - 1:

let message = "Hello world";
let length = message.length;

// Printing the last character:
console.log(message[length - 1]); // Output: d

// Printing the second to last character:
console.log(message[length - 2]); // Output: l

In general, if you want the nth last character, you access message[length - n].


Slicing characters from the end:

The length is also useful for slicing some characters from the end of a string:

let message = "Hello world";
let length = message.length;

// Slicing last 4 characters:
let lastChars = message.slice(length - 4);
console.log(lastChars); // Output: orld

// Slicing last 7 characters:
lastChars = message.slice(length - 7);
console.log(lastChars); // Output: o world

In general, if you want the last n characters, you use message.slice(length - n).


Assignment
Follow the Coding Tutorial and let's practice with string length!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check