Help us test MDN's new front-end: https://discourse.mozilla.org/t/help-us-test-mdns-new-react-front-end-beta/42593

我們的志工尚未將本文翻譯為 正體中文 (繁體) 版本。加入我們,幫忙翻譯!
您也可以閱讀本文的 English (US) 版本。

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

Syntax

string.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. In Firefox, strings have a maximum length of 2**30 - 2 (~1GB). In versions prior to Firefox 65, the maximum length was 2**28 - 1 (~256MB).

For an empty string, length is 0.

The static property String.length returns the value 1.

Examples

Basic usage

let x = 'Mozilla';
let empty = '';

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

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

Assigning to length

let myString = "bluebells";

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

Specifications

Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.0.
ECMAScript 5.1 (ECMA-262)
The definition of 'String.prototype.length' in that specification.
Standard
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'String.prototype.length' in that specification.
Standard
ECMAScript Latest Draft (ECMA-262)
The definition of 'String.prototype.length' in that specification.
Draft

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
lengthChrome Full support YesEdge Full support 12Firefox Full support 1IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes

Legend

Full support  
Full support

See also