user5818995
user5818995

Reputation:

How to get the number of characters in a javascript string

string.length returns the number of 16-bit characters in a string, thus the length of a string '1.2 in exponent is 1.2e0' is 25, because the e (\udc52) is 17-bit and is treated as 2 different unicode characters. This behavior may be useful for most of the cases in programming, what if I want to know the exact number of characters in a string (like, in the example above, 24 instead of 25). Is there a predefined method, tricks, hacks, or anything to count number of characters instead of number of 16-bit characters?

Note: The e in the example string is not alphabetic character E, it is the character that represents 'exponent' in IEEE 754 format

Upvotes: 3

Views: 1814

Answers (1)

Sebastian
Sebastian

Reputation: 1820

In ES6, you can use Array.from():

var string = "1.2 in exponent is 1.2𝑒0";
var charCount = Array.from(string).length;
console.log(charCount); // returns 24

Upvotes: 1

Related Questions