W3cubDocs

/JavaScript

string.length

The length property of a String object indicates the length of a string, in UTF-16 code units.

Syntax

str.length

Description

This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string.

ECMASCript 2016 (ed. 7) established a maximum length of 2^53 - 1 elements. Previously, no maximum length was specified.

For an empty string, length is 0.

The static property String.length returns the value 1.

Examples

Basic usage

var x = 'Mozilla';
var empty = '';

console.log('Mozilla is ' + x.length + ' code units long');
/* "Mozilla is 7 code units long" */

console.log('The empty string has a length of ' + empty.length);
/* "The empty string has a length of 0" */

Assigning to length

var myString = "bluebells";

// Attempting to assign a value to a string's .length property has no observable effect. 
myString.length = 4;
console.log(myString);
/* "bluebells" */

Specifications

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
Basic support Yes Yes 1 Yes Yes Yes
Mobile
Android webview Chrome for Android Edge Mobile Firefox for Android Opera for Android iOS Safari Samsung Internet
Basic support Yes Yes Yes 4 Yes Yes Yes
Server
Node.js
Basic support Yes

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length