How do you get the length of a string?

Viewed 625144

How do you get the length of a string in jQuery?

10 Answers

You don't need jquery, just use yourstring.length. See reference here and also here.

Update:

To support unicode strings, length need to be computed as following:

[...""].length

or create an auxiliary function

function uniLen(s) {
    return [...s].length
}

The easiest way:

$('#selector').val().length

jQuery is a JavaScript library.

You don't need to use jQuery to get the length of a string because it is a basic JavaScript string object property.

somestring.length;

You don't need to use jquery.

var myString = 'abc';
var n = myString.length;

n will be 3.

It's not jquery you need, it's JS:

alert(str.length);

same way you do it in javascript:

"something".length

In some cases String.length might return a value which is different from the actual number of characters visible on the screen (e.g. some emojis are encoded by 2 UTF-16 units):

MDN says: 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.

In Unicode separate visible characters are called graphemes. In case you need to account for this case, you'll need some lib that can split the string into graphemes, such as this: https://www.npmjs.com/package/grapheme-splitter

Related