字串轉十六進制
var str = 'https://www.qq.com';
var arr = [];
for (var i = 0; i < str.length; i++) {
arr.push(str.charCodeAt(i).toString(16));
}
console.log('x' + arr.join('x')); // x68x74x74x70x3ax2fx2fx77x77x77x2ex71x71x2ex63x6fx6d
十六進制轉字串
var hex = 'x68x74x74x70x3ax2fx2fx77x77x77x2ex71x71x2ex63x6fx6d';
// 在 Chrome Console 或 Firebug 直接貼上並按 Enter 即可看到原字串
// 或用 JS 解析:
var str = hex.replace(/x([0-9a-fA-F]{2})/g, function(_, h) {
return String.fromCharCode(parseInt(h, 16));
});
console.log(str); // https://www.qq.com
應用場景
- URL 參數編碼、簡易混淆、傳遞特殊字符。
- 注意:這不是加密,僅為編碼,不可用於敏感資料保護。
ES6 簡寫
// 字串 -> Hex
const toHex = s => [...s].map(c => c.charCodeAt(0).toString(16).padStart(2,'0')).join('');
// Hex -> 字串
const fromHex = h => h.match(/.{2}/g).map(b => String.fromCharCode(parseInt(b,16))).join('');