JavaScript
// Method 1: Using length property
let str = "Hello World";
console.log("String:", str);
console.log("Length:", str.length);
// Method 2: Manual count using loop
function stringLength(str) {
let count = 0;
for (let i = 0; i < str.length; i++) {
count++;
}
return count;
}
console.log("\nManual count:", stringLength("JavaScript"));
// Method 3: Using split and length
function stringLengthSplit(str) {
return str.split('').length;
}
console.log("Using split:", stringLengthSplit("Programming"));
// Method 4: Count without spaces
function stringLengthNoSpaces(str) {
return str.replace(/\s/g, '').length;
}
console.log("\nLength without spaces:", stringLengthNoSpaces("Hello World"));
// Method 5: Count words
function countWords(str) {
return str.trim().split(/\s+/).length;
}
console.log("Word count:", countWords("Hello World from JavaScript"));Output
String: Hello World Length: 11 Manual count: 10 Using split: 11 Length without spaces: 10 Word count: 4
This program demonstrates different ways to find string length.
Method 1: Length Property
Built-in property:
javascriptstr.length;
Returns: Number of characters (including spaces)
Method 2: Manual Count
Using loop:
javascriptlet count = 0; for (let i = 0; i < str.length; i++) { count++; }
Method 3: Split and Length
Convert to array:
javascriptstr.split('').length;
Split Method:
- Converts string to array
- Each character becomes array element
Method 4: Length Without Spaces
Remove spaces first:
javascriptstr.replace(/\s/g, '').length;
Regular Expression:
/\s/g: Matches all whitespaceg: Global flag (all occurrences)
Method 5: Word Count
Count words, not characters:
javascriptstr.trim().split(/\s+/).length;
String Methods:
trim(): Removes leading/trailing spacessplit(/\s+/): Splits on one or more spaces
Important Notes:
lengthis a property, not a method- Returns number of UTF-16 code units
- Special characters may count as 2
When to Use:
-
length property: Standard, fastest
-
Manual count: Learning
-
Split: When you need array anyway