js实现cencode
以下是使用JavaScript实现类似C语言中cencode功能的几种方法,主要用于字符串或数据的编码转换:
使用encodeURIComponent进行URL编码
该方法适用于对URL参数部分进行编码,保留特殊字符(如- _ . ! ~ * ' ( )):

const str = "Hello World!@#";
const encodedStr = encodeURIComponent(str);
console.log(encodedStr); // 输出: "Hello%20World!%40%23"
使用btoa进行Base64编码
适用于二进制数据或简单字符串的Base64编码:

const text = "Hello Base64";
const encodedData = btoa(text);
console.log(encodedData); // 输出: "SGVsbG8gQmFzZTY0"
自定义十六进制编码
实现类似C语言中逐字符转十六进制的效果:
function hexEncode(str) {
let result = '';
for (let i = 0; i < str.length; i++) {
const hex = str.charCodeAt(i).toString(16);
result += ('000' + hex).slice(-4); // 补零至4位
}
return result;
}
console.log(hexEncode("ABC")); // 输出: "004100420043"
使用TextEncoder进行UTF-8编码
现代浏览器支持的API,可获取UTF-8字节数组:
const encoder = new TextEncoder();
const uint8Array = encoder.encode("你好");
console.log(Array.from(uint8Array)); // 输出: [228, 189, 160, 229, 165, 189]
注意事项
- URL编码时
encodeURI不会编码/?:@&=+$#等完整URL需要的字符,而encodeURIComponent会编码这些字符 btoa仅支持Latin1字符集,对中文需先进行URI编码:btoa(encodeURIComponent("中文")); // 正确做法
以上方法可根据实际需求选择,分别对应不同的编码场景。






