How to get length of string in javascript?

Software
AffiliatePal is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Listen

Introduction

In JavaScript, getting the length of a string is a common task that can be accomplished using a built-in property called `length`. This property returns the number of characters in a string, allowing developers to perform various operations based on the length of a string. In this article, we will explore different methods to get the length of a string in JavaScript and discuss their usage.

Using the length property

The most straightforward way to get the length of a string in JavaScript is by using the `length` property. This property is available on all string objects and returns the number of characters in the string. Here’s an example:

“`javascript
const str = “Hello, World!”;
const length = str.length;
console.log(length); // Output: 13
“`

In the above example, the `length` property is accessed using dot notation on the `str` string object. The value of `length` is then printed to the console, which in this case is `13`.

It’s important to note that the `length` property returns the number of characters in a string, including spaces and punctuation marks.

Handling empty strings

When dealing with empty strings, the `length` property returns `0`. This can be useful when validating user input or checking if a string is empty. Here’s an example:

“`javascript
const emptyStr = “”;
const isEmpty = emptyStr.length === 0;
console.log(isEmpty); // Output: true
“`

In the above example, the `isEmpty` variable is assigned the result of comparing the length of `emptyStr` with `0`. Since the length is `0`, the comparison returns `true`, indicating that the string is empty.

Handling Unicode characters

JavaScript supports Unicode characters, and the `length` property handles them correctly. Each Unicode character is considered as one character, regardless of its visual representation. Here’s an example:

“`javascript
const unicodeStr = “👋🌍”;
const length = unicodeStr.length;
console.log(length); // Output: 2
“`

In the above example, the `unicodeStr` contains two Unicode characters, a waving hand emoji and a globe emoji. Despite their visual complexity, the `length` property correctly returns `2` as the number of characters in the string.

Conclusion

Getting the length of a string in JavaScript is a simple task using the `length` property. By accessing this property on a string object, developers can obtain the number of characters in a string. This information can be used for various purposes, such as validation, manipulation, or displaying character counts.

References

– developer.mozilla.org: [String.prototype.length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length)