How to get the string length in bytes in nodejs?

前端 未结 4 970
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 12:03

How to get the string length in bytes in nodejs? If I have a string, like this: äáöü then str.length will return with 4. But how to get that, how many bytes form th

相关标签:
4条回答
  • 2021-02-01 12:41
    function getBytes(string){
      return Buffer.byteLength(string, 'utf8')
    }
    
    0 讨论(0)
  • 2021-02-01 12:45

    If you want to specific encoded, here is iconv example

      var iconv = require('iconv-lite');
      var buf =iconv.encode('äáöü', 'utf8');
      console.log(buf.length);
      // output: 8
    
    0 讨论(0)
  • 2021-02-01 12:53

    Alternatively, you can use TextEncoder

    new TextEncoder().encode(str).length
    

    Related question

    Assume it's slower though

    0 讨论(0)
  • 2021-02-01 13:02

    Here is an example:

    str = 'äáöü';
    
    console.log(str + ": " + str.length + " characters, " +
      Buffer.byteLength(str, 'utf8') + " bytes");
    
    // äáöü: 4 characters, 8 bytes
    

    Buffer.byteLength(string, [encoding])

    0 讨论(0)
提交回复
热议问题