Wednesday, 13 November 2024

How to find number of characters in a string in JavaScript?

The length property in JavaScript is mostly used feature when working with strings. It allows you to determine the number of characters in a string, which is essential for various string manipulation tasks like validation, iteration, and formatting.

 

The length property returns the total number of UTF-16 code units in a string. This effectively corresponds to the number of characters in the string, including spaces, punctuation, and special characters.

 

Syntax

str.length

 

Example

let str = "Hello, World!";
let lengthOfString = str.length;
console.log(lengthOfString); // Outputs: 13

The length property is read-only. You cannot modify it directly. It simply reflects the number of characters in the string. Attempting to assign a value to it will have no effect.

let str = "Hello";
str.length = 10;
console.log(str.length); // Outputs: 5

Handling Multibyte Characters

The length property counts UTF-16 code units, meaning it may not correctly reflect the actual number of visible characters when dealing with multibyte characters (like emojis or certain non-Latin scripts).

 

For example

let str = "😊";
console.log(str.length); // Outputs: 2

Empty Strings

For an empty string (""), the length property returns 0.

let emptyStr = "";
console.log(emptyStr.length); // Outputs: 0

Usage in Validation

The length property is commonly used to validate user input, such as ensuring passwords meet a minimum length requirement:

let password = "abc123";
if (password.length >= 8) {
    console.log("Password is long enough.");
} else {
    console.log("Password is too short.");
}

Iterating Over Characters

You can use the length property in loops to iterate over each character in a string.

let str = "JavaScript";
for (let i = 0; i < str.length; i++) {
    console.log(str[i]);
}

stringLength.js

let str = "Hello, World!";
let lengthOfString = str.length;
console.log(`String : ${str}, length : ${lengthOfString}`);

str = "Hello";
str.length = 10;
console.log(`String : ${str}, length : ${str.length}`);

str = "😊";
console.log(`String : ${str}, length : ${str.length}`);

str = "";
console.log(`String : ${str}, length : ${str.length}`);

let password = "abc123";
if (password.length >= 8) {
    console.log("Password is long enough.");
} else {
    console.log("Password is too short.");
}

str = "JavaScript";
for (let i = 0; i < str.length; i++) {
    console.log(str[i]);
}

Output

String : Hello, World!, length : 13
String : Hello, length : 5
String : 😊, length : 2
String : , length : 0
Password is too short.
J
a
v
a
S
c
r
i
p
t

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment