String Length

Program to find length of a string

JavaScriptBeginner
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:

javascript
str.length;

Returns: Number of characters (including spaces)

Method 2: Manual Count

Using loop:

javascript
let count = 0;
for (let i = 0; i < str.length; i++) {
    count++;
}

Method 3: Split and Length

Convert to array:

javascript
str.split('').length;

Split Method:

  • Converts string to array
  • Each character becomes array element

Method 4: Length Without Spaces

Remove spaces first:

javascript
str.replace(/\s/g, '').length;

Regular Expression:

  • /\s/g: Matches all whitespace
  • g: Global flag (all occurrences)

Method 5: Word Count

Count words, not characters:

javascript
str.trim().split(/\s+/).length;

String Methods:

  • trim(): Removes leading/trailing spaces
  • split(/\s+/): Splits on one or more spaces

Important Notes:

  • length is 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