The “length” property of a string returns the number of characters contained in a string. This count includes spaces, numbers, symbols, and all other characters, each counting as one character, even if the character might be represented by more than one byte in memory.
Syntax:
The syntax for retrieving the length of a string is straightforward:
let string = "Hello, World!";
let length = string.length;
console.log(length); // Outputs: 13
It’s important to note that the “length” property returns a value of type number, representing the count of characters starting from 1. Also, it’s a read-only property, meaning you cannot change the length of a string directly using this property.
Examples and Execution:
Let’s dive into practical examples that you can run directly in your JavaScript environment. These examples cover different scenarios to give a comprehensive understanding of how the “length” property works.
Basic Usage:
let message = "Hello, JavaScript!";
console.log(message.length); // Outputs: 18
Empty String
let emptyString = "";
console.log(emptyString.length); // Outputs: 0
String with Spaces:
let spacedString = " JavaScript ";
console.log(spacedString.length); // Outputs: 14 (includes all spaces)
Unicode Characters
let unicodeString = "😊🌟✨";
console.log(unicodeString.length); // Outputs: 6 (each emoji consists of 2 surrogate pairs)
Dynamic Computation:
function isStringTooLong(string, maxLength) {
return string.length > maxLength;
}
let myString = "This is a test string.";
let maxLength = 20;
console.log(isStringTooLong(myString, maxLength)); // Outputs: true
The function ‘isStringTooLong’ dynamically checks if the provided string exceeds a certain length, showcasing a practical application of the “length” property.
Get more articles on Java Script
Read more on Shell and Linux related articles
Refer more on python here : Python