String Length
Program to find length of a string
JavaScript String Length Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// 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"));String: Hello World Length: 11 Manual count: 10 Using split: 11 Length without spaces: 10 Word count: 4
Understanding String Length
This program demonstrates different ways to find string length.
Method 1: Length Property
Built-in property:
str.length;
Returns:
Number of characters (including spaces)
Method 2: Manual Count
Using loop:
let count = 0;
for (let i = 0; i < str.length; i++) {
count++;
}
Method 3: Split and Length
Convert to array:
str.split('').length;
Split Method:
Method 4: Length Without Spaces
Remove spaces first:
str.replace(/\s/g, '').length;
Regular Expression:
/\s/g: Matches all whitespaceg: Global flag (all occurrences)Method 5: Word Count
Count words, not characters:
str.trim().split(/\s+/).length;
String Methods:
trim(): Removes leading/trailing spacessplit(/\s+/): Splits on one or more spacesImportant Notes:
length is a property, not a methodWhen to Use:
-
length property
: Standard, fastest
-
Manual count
: Learning
-
Split
: When you need array anyway
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.