How to calculate byte length containing UTF8 characters using javascript?

前端 未结 3 1843
春和景丽
春和景丽 2021-02-13 21:35

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

3条回答
  •  旧时难觅i
    2021-02-13 21:44

    The experimental TextEncoder API can be used for this but is not supported by Internet Explorer or Safari:

    (new TextEncoder()).encode("i ♥ u i ♥ u i ♥ u i ♥ u i ♥ u").length;
    

    Another alternative is to URI-encode the string and count characters and %-encoded escape sequences, as in this library:

    ~-encodeURI("i ♥ u i ♥ u i ♥ u i ♥ u i ♥ u").split(/%..|./).length
    

    The github page has a compatibility list which unfortunately does not include IE10, but IE9.

    Since I can not yet comment, I'll also note here that the solution in the accepted answer does not work for code points consisting of multiple UTF-16 code units.

提交回复
热议问题