A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-string-length-property/ below:

JavaScript String length Property - GeeksforGeeks

JavaScript String length Property

Last Updated : 29 Oct, 2024

The JavaScript length property is a fundamental feature used to determine the number of characters in a string. It is essential for various string operations, such as validation, manipulation, and iteration. Understanding how to effectively use the length property can simplify tasks like checking input lengths, truncating strings, and dynamically adjusting content.

Syntax

The syntax for using the length property is straightforward and applies directly to any string variable:

string.length
Examples of JS String Length Property

Here are examples demonstrating how the length property is used in JavaScript:

Example 1: Measuring the Length of a Basic String

In this example, the string "GFG" contains three characters, so length returns 3.

JavaScript
// JavaScript to illustrate length property    
function func() {

    // length property for string
    console.log("GFG".length)
}
func();
Example 2: Checking if a String is Empty

Here, we declare an empty string, emptyString, and use the length property to confirm if its length is 0. Since the string is empty, the comparison returns true.

JavaScript
let emptyString = '';

console.log(emptyString.length === 0);
Example 3: Accessing the Last Character of a String

For the string str = "GeeksforGeeks", we can find the index of the last character by subtracting 1 from the string’s length. Since indexing starts at 0, the final index is 12.

JavaScript
let str = 'GeeksforGeeks';

const lastIndex = str.length - 1;
console.log(lastIndex); 

The JavaScript length property is essential for working with strings efficiently. It helps with tasks like validating input, processing data, and adjusting content dynamically. This property makes string operations simpler and more accurate in your projects.

Supported Browsers

The length property is well-supported across all major browsers, making it a reliable option in web development:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4