Explain Codes LogoExplain Codes Logo

How do you get the length of a string?

javascript
string-length
unicode
spread-operator
Anton ShumikhinbyAnton Shumikhin·Jan 4, 2025
TLDR

To retrieve a string's length in JavaScript, use the .length property to count characters:

let length = "Sample text".length; // No, it's not an IQ test, just a character count, I promise. Outputs: 11

If you are dealing with unicode characters, it's a bit trickier, mate. Use the spread operator to get the actual length:

let unicodeStringLength = [..."𠮷"].length; // Don't be fooled by unicodes. Outputs: 1 instead of 2

Honestly, having a helper function like uniLen(s) at hand is a lifesaver for these unicode shenanigans.

Unicode, why you do this?

Unicode and JavaScript

All the unicodery (yeah, I made that up) makes counting characters kinda tricky. Here's how you do it:

const uniLen = s => [...s].length; console.log(uniLen("𠮷𠮷")); // Not-So-UniLength: kudos to spread operator. Outputs: 2

When efficiency wins

The spread operator takes up processing power (Yeah, it gets tired too, you know). So for ASCII strings, just go old school:

let length = "Your string here".length; // Back to basics. Boring, but quick.

jQuery - A love story

Substring lengths in jQuery

With jQuery around, everything is easier, even getting a peek at string's length:

let textLength = $('#selector').text().length; // I see your length, text string! 🕶️

Input value string length

Input values are a bit sly, but we can tackle that too:

let inputLength = $('#selector').val().length; // I *value* your length, input string! 😉

Make sure to pay attention to your selectors. Avoid selection blunders for accurate results.

Watch out for the curveballs

Spaces & Newlines are cheeky

.length counts spaces and newlines too. Use trim() to weed them out:

let trimmedLength = " You cheeky string\n".trim().length; // Can't fool me with those spaces and newlines. Ha!

Empty & null strings - The Nullity Bunch

.length will cozy up to 0 if the string's empty. And if you dare call .length of null or undefined, it will throw a TypeError tantrum.

Some pearls of wisdom

Embrace native JS

When it comes to getting a string's length, jQuery is like using a sledgehammer to crack a nut. Native JavaScript .length is less verbose, more efficient.

Alert: Avoid getting too alert()

Using alert() to display string length is fine for quick debugging, but it's better to log to console or update DOM elements for user feedback.