JavaScript String length

The JavaScript String length property returns the number of characters in a string.

The syntax to access the length property of a String object is:

str.length

Here, str is a string.


Example 1: Finding Number of Characters in a String

// get string length
var sentence = "";
len = sentence.length;
console.log(len); // 0

sentence = "I love Programiz.";
len = sentence.length;
console.log(len); // 17

// no effect if try to assign value to length
sentence.length = 5;

console.log(sentence); // I love Programiz.

Output

0
17
I love Programiz.

Here, we can see that length property returns the number of characters in each string.

Notes:

  • The String.length property is a read-only property. There will be no effect if we try to change it manually.
  • The String.length property actually returns the code units in the UTF-16 string format. Some rare string characters require two code units to be represented. Due to this, the length property might not always return the number of characters.