Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate byte length containing UTF8 characters using javascript?

I have textbox, in which the user can enter the characters in ASCII/UTF-8 or a combination of both. Is there any API in javascript which we can calculate the length of string in bytes for the characters entered in textbox.

Like if i enter ascii chacter let's say : mystring - the length would be calculated as 8. But when UTF8 characters are entered the characters can be 2/3/4 byte.

lets say the character entered : i ♥ u , the length in bytes is 5.

The textbox can accept max length of 31 characters. But in case if UTF8 characters entered, it will not accept character string : i ♥ u i ♥ u i ♥ u i ♥ u i ♥ u . the length is 30.

Can we restrict the user to enter characters not more than 31 even for UTF8 characters.

like image 304
k00989 Avatar asked Sep 23 '14 11:09

k00989


1 Answers

As of 2018, the most compatible and reliable way of doing this seems to be with the blob api.

new Blob([str]).size

Even supported in IE10 if anyone uses that anymore.

like image 141
recursive Avatar answered Oct 20 '22 12:10

recursive