Open In App

TypeScript String Length Property

Last Updated : 15 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The length property in TypeScript is a read-only attribute used to get the number of characters in a string, including spaces and special characters. It returns an integer representing the total length of the string.

Syntax

string.length 

Return Value: This method returns the length to the String function that created the object. 

The examples below illustrate the String Length Property in TypeScript

Example 1: Getting the Length of a String

In this example, we retrieve the length of str using length, which counts characters including spaces,

TypeScript
let str: string = "TypeScript is a powerful language";
let length: number = str.length;

console.log("Return Value of Length property:", length);

Output: 

Return Value of Length property: 33

Example 2: Length of an Empty String

In this example we are calculates the length of emptyStr, which is an empty string. The result is 0, indicating no characters are present in the string.

TypeScript
let emptyStr: string = "";
let emptyLength: number = emptyStr.length;

console.log("Length of an empty string:", emptyLength);

Output: 

Length of an empty string: 0

Example 3: Length of a String with Special Characters

In this example we calculates the length of specialStr, which includes special characters and emojis, resulting in 13 for “Hello, #!”, counting each character individually.

TypeScript
let specialStr: string = "Hello, #!";
let specialLength: number = specialStr.length;

console.log("Length of string with special characters:", specialLength);

Output:

Length of string with special characters: 9

Next Article

Similar Reads