js实现编码
编码转换方法
使用encodeURIComponent()对URL进行编码,该方法会将特殊字符(如/, ?, &, =等)转换为UTF-8编码的转义序列:
const encoded = encodeURIComponent('测试/string?param=1');
console.log(encoded); // 输出 "%E6%B5%8B%E8%AF%95%2Fstring%3Fparam%3D1"
Base64编码
通过btoa()实现Base64编码,注意该方法仅支持Latin1字符集:
const base64Encoded = btoa('Hello World');
console.log(base64Encoded); // 输出 "SGVsbG8gV29ybGQ="
处理中文需先进行URI编码转换:
const chineseBase64 = btoa(encodeURIComponent('你好'));
console.log(chineseBase64); // 输出 "JUU0JUJEJUEwJUU1JUE1JUJE"
十六进制编码
将字符串转换为十六进制表示形式:
function toHex(str) {
return str.split('').map(c =>
c.charCodeAt(0).toString(16).padStart(2, '0')
).join('');
}
console.log(toHex('ABC')); // 输出 "414243"
HTML实体编码
转换特殊字符为HTML实体:
function htmlEncode(str) {
return str.replace(/[&<>'"]/g, tag => ({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag]));
}
console.log(htmlEncode('<div>"test"</div>'));
// 输出 "<div>"test"</div>"
注意事项
encodeURI()与encodeURIComponent()区别:前者保留完整URL结构,后者编码所有特殊字符- 二进制数据编码建议使用
TextEncoderAPI:const encoder = new TextEncoder(); const uint8Array = encoder.encode('文本'); - 解码操作使用对应方法:
decodeURIComponent(),atob(),TextDecoder等







