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
length is a property, not a function, so do not write length().
const empty = "";
console.log(empty.length); // 0
Indexes start at 0, so the final valid index is length - 1.
const word = "JavaScript";
console.log(word[word.length - 1]); // t
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}`;
});
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.
const value = " hello ";
console.log(value.length); // 9
console.log(value.trim().length); // 5
length() as though it were a method.text[text.length] for the last character instead of text[text.length - 1].String Reference Uppercase Strings
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Nibedita Sahu | 18-01-2011 |
| How to remove blank spaces between two characters using javascript | |