JavaScript String length Property

The JavaScript length property returns the number of UTF-16 code units in a string. It is available directly on every string value.

const text = "Hello world!";
console.log(text.length); // 12

Spaces and punctuation count because they are part of the string.

String length Syntax Top ↑

string.length

length is a property, not a function, so do not write length().

Length of an Empty String Top ↑

const empty = "";
console.log(empty.length); // 0

Last Character and Valid String Indexes Top ↑

Indexes start at 0, so the final valid index is length - 1.

const word = "JavaScript";
console.log(word[word.length - 1]); // t

Count Characters Entered by a User Top ↑

This modernizes the original page demo without inline JavaScript handlers.

const input = document.getElementById("text1");
const message = document.getElementById("msg");

document.getElementById("checkLength").addEventListener("click", () => {
  message.textContent = `The length of data = ${input.value.length}`;
});

String Length with Emoji and Unicode Top ↑

length counts UTF-16 code units, not always visible characters. Some emoji and other characters use two code units.

const symbol = "😀";
console.log(symbol.length);          // 2
console.log([...symbol].length);     // 1 code point

Even spread syntax counts Unicode code points rather than every possible user-perceived grapheme cluster, so complex emoji sequences can still require Intl.Segmenter when exact visual-character counting matters.

Length Before and After trim() Top ↑

const value = "  hello  ";
console.log(value.length);        // 9
console.log(value.trim().length); // 5

Common String length Mistakes Top ↑

  • Calling length() as though it were a method.
  • Forgetting that spaces and punctuation count.
  • Using text[text.length] for the last character instead of text[text.length - 1].
  • Assuming UTF-16 code-unit length always equals visible character count.

String Reference Uppercase Strings




Subscribe to our YouTube Channel here



plus2net.com







Nibedita Sahu

18-01-2011

How to remove blank spaces between two characters using javascript



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer