JavaScript字符串转UTF-8编码:方法详解
在JavaScript中,字符串是以UTF-16编码存储的。如果你想将字符串转换为UTF-8编码,可以使用以下方法:
- 使用TextEncoder API:
const encoder = new TextEncoder();
const utf8Array = encoder.encode('yourString');
const utf8String = String.fromCharCode.apply(null, utf8Array);
- 使用encodeURIComponent函数:
const utf8String = encodeURIComponent('yourString');
请注意,使用encodeURIComponent函数转换的结果是URL编码的字符串,而不是严格的UTF-8编码。如果你需要严格的UTF-8编码,请使用TextEncoder API。
希望对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/cP4Y 著作权归作者所有。请勿转载和采集!