TypeScript String length
Syntax & Examples
String.length property
The `length` property of a String object represents the number of characters in the string, including spaces, punctuation, and other special characters.
Syntax of String.length
The syntax of String.length property is:
length: number
This length property of String returns the length of the string, which is a non-negative integer.
Return Type
String.length returns value of type number
.
✐ Examples
1 Using the length property to get the string length
You can use the `length` property to determine the number of characters in a string.
For example,
- Define a string variable
str
with some text. - Access the
length
property of the string. - Store the length in a variable or use it directly in your logic.
- Log the length to the console using the
console.log()
method.
TypeScript Program
const str = 'Hello, World!';
const length = str.length;
console.log(length);
Output
13
2 Using length property with an empty string
The `length` property of an empty string is always 0.
For example,
- Define an empty string variable
emptyStr
. - Access the
length
property of the empty string. - Log the length to the console using the
console.log()
method.
TypeScript Program
const emptyStr = '';
console.log(emptyStr.length);
Output
0
3 Using the length property for string manipulation
The `length` property can be used to dynamically determine the range of a loop for iterating through each character in a string.
For example,
- Define a string variable
str
with some text. - Use a for loop with the condition based on
str.length
. - Log each character to the console using the loop.
TypeScript Program
const str = 'Hello';
for (let i = 0; i < str.length; i++) {
console.log(str[i]);
}
Output
H E L L O
Summary
In this TypeScript tutorial, we learned about length property of String: the syntax and few working examples with output and detailed explanation for each example.