js string转.toUtf8()
时间: 2024-04-25 08:23:27 浏览: 109
根据提供的引用内容,可以使用以下代码将JavaScript中的字符串转换为UTF-8编码的字节数组:
```javascript
function strToUtf8Bytes(text) {
const code = encodeURIComponent(text);
const bytes = \[\];
for (let i = 0; i < code.length; i++) {
const c = code.charAt(i);
if (c === '%') {
const hex = code.charAt(i + 1) + code.charAt(i + 2);
const hexval = parseInt(hex, 16);
bytes.push(hexval);
i += 2;
} else {
bytes.push(c.charCodeAt(0));
}
}
return bytes;
}
```
如果你想将UTF-8格式的字节数组转换回字符串,可以使用以下代码:
```javascript
function utf8BytesToStr(bytes) {
let text = '';
for (let i = 0; i < bytes.length; i++) {
text += '%' + bytes\[i\].toString(16);
}
return decodeURIComponent(text);
}
```
希望这些代码能够帮助你实现JavaScript字符串转换为UTF-8编码的功能。
#### 引用[.reference_title]
- *1* *2* *3* [js 前端String 转 utf8 ArrayBuffer,utf8 转String](https://blog.csdn.net/weixin_43130350/article/details/122335034)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文