Count bytes in textarea using javascript

后端 未结 10 609
难免孤独
难免孤独 2020-12-02 11:15

I need to count how long in bytes a textarea is when UTF8 encoded using javascript. Any idea how I would do this?

thanks!

10条回答
  •  一生所求
    2020-12-02 11:21

    [June 2020: The previous answer has been replaced due to it returning incorrect results].

    Most modern JS environments (browsers and Node) now support the TextEncoder API, which may be used as follows to count UTF8 bytes:

    const textEncoder = new TextEncoder();
    textEncoder.encode('⤀⦀⨀').length; // => 9
    

    This is not quite as fast as the getUTF8Length() function mentioned in other answers, below, but should suffice for all but the most demanding use cases. Moreover, it has the benefit of leveraging a standard API that is well-tested, well-maintained, and portable.

提交回复
热议问题