javascript - 我不明白计算/javascript 的字符串到字节方面

标签 javascript string byte

两年后回到这个/另一个话题,我看到人们在讨论同样的话题;我还是不明白这是怎么回事。

按照这个SO帖子:

String length in bytes in JavaScript

I want to understand this part of javascript! I am also interested in calculating the kb size of a bitcoin transaction before I push it to the blockchain. The more important of the two though is that I finally understand what these users are doing because its come up more than once and I just don't get it!

我已经尝试了作为答案概述的三个函数,但它们似乎都只是返回 string.length 而我希望它们返回不同的值(字符串的开销以字节/千字节/兆字节为单位) )

function byteCount(s) {
    return encodeURI(s).split(/%..|./).length - 1;
    }

console.log(byteCount('hello'),'hello'.length);//5,5


function getLengthInBytes(str) {
    var b = str.match(/[^\x00-\xff]/g);
    return (str.length + (!b ? 0: b.length)); 
    }

console.log(getLengthInBytes('hello'),'hello'.length);//5,5


console.log((new TextEncoder('utf-8').encode('hello')).length,'hello'.length);//5,5

这对我来说毫无意义,这很烦人!显然这些人不会谈论如何获得他们可以通过 string.length 轻松获得的东西 那么他们正在尝试并成功返回什么?

字符串应该是二进制的吗? (像这样:How to convert text to binary code in JavaScript?)

最佳答案

世界上有很多不同的标志。 它们不适合一个字节的数据。这就是为什么某些字符使用多个字节的数据的原因。 一些示例:“Aüöôś”

关于javascript - 我不明白计算/javascript 的字符串到字节方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38317328/

相关文章:

javascript - 重构 jQuery 代码时,为什么我得到的是 [object Object] 而不是我预期的 HTML?

c - 左填充文本

c# - 字符串到字节数组(到字符串到 XML)并再次返回

google-app-engine - 将十六进制值存储为字节导致丢失

javascript - mvc3 如何在不刷新页面的情况下返回 View

javascript - 为什么在 ASP.NET MVC 中我得到 JSON 而不是 FileDownload?

javascript - 有没有办法在nodejs中加载特定模块?

c++ - union 成员有一个重要的复制构造函数

c# - 将数据类型 'long' 转换为字节数组

java - 我怎样才能在java中连接两个字节?