JavaScript 如何获取字符串的字节数
任务: 找到给定字符串的字节数。
示例:
Input : "GeeksForGeeks"
Output : 13 bytes
Input : 20€
Output : 5 bytes
Input : "????"
Output : 4 bytes
为了实现这一点,我们有两种方式,第一种是使用Blob API,第二种是Buffer API,第一种适用于浏览器,第二种适用于Node.js环境。
blob对象只是一组字节,用于保存文件中存储的数据。使用blob读取字符串的字节时,我们创建一个Blob对象的新实例,然后将字符串传递给它,通过使用size属性,我们可以获得字符串的字节。
示例1:使用Blob API
<script>
const len = (str) => {
// Creating new Blob object and passing string into it
// inside square brackets and then
// by using size property storin the size
// inside the size variable
let size = new Blob([str]).size;
return size;
}
console.log(len("Geeksforgeeks"))
console.log(len("true"))
console.log(len("false"))
console.log(len("12345"))
console.log(len("20€"))
console.log(len("????"))
</script>
输出:
13
4
5
5
5
4
示例2:使用Buffer API
现在在NodeJS中有另一种方法可以实现这一点,即使用Buffer。首先创建Buffer对象,然后将字符串放入其中,并使用length属性可以获取字符串的大小
<script>
const len = (str) => {
let size = Buffer.from(str).length;
return size;
}
console.log(len("Geeksforgeeks"))
console.log(len("true"))
console.log(len("false"))
console.log(len("12345"))
console.log(len("20€"))
console.log(len("????"))
</script>
输出:
13
4
5
5
5
4
极客教程