How to Use the String length Property in JavaScript

  • 2 min read
  • December 6, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

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

const str = 'Get the length of this string';
console.log(str.length);
// Expected output: 29

In the example above, str is a String containing 29 characters.

The length property counts all characters, including blank spaces and special characters.

Knowing the length of a String is useful in multiple different scenarios:

  • Looping through a string with a for statement
  • Displaying a shortened version of a string if the text is too long
  • Verifying that a certain number of characters were entered for an input (e.g. username or password)

There are many more scenarios where String.length is useful – the only limit is your imagination.

Syntax

The syntax of the String object’s length property is as follows:

String.length

This property returns the length of the associated string.

The length of an empty string is 0 (zero).

The maximum length of a String is the maximum value of the Number data type, which in most cases is 253 – 1 (note: the maximum value of the Number data type can vary based on the underlying implementation of the JavaScript standard).

 

Related Articles

JavaScript – How to Use the Array length property

JavaScript – How to Use the toString Method

JavaScript – How to Use the indexOf Method

Related Posts

How to Change The Page URL with JavaScript

How to Change The Page URL with JavaScript

Redirecting to a URL is one of the most common activities performed by JavaScript. As such, JavaScript offers multiple different ways to support redirects from the

How to Use the toUpperCase() Method in JavaScript

How to Use the toUpperCase() Method in JavaScript

JavaScript’s toUpperCase() method converts a string object into a new string consisting of the contents of the first string, with all alphabetic characters converted to be

How to Use the void operator in JvaScript

How to Use the void operator in JvaScript

The void operator evaluates a given expression and then returns undefined. If void operates on an expression which produces a value it will always return undefined.