把字串轉成十六進位表示,說穿了就是逐字取 charCode 再換底數。注意這只是編碼,不具任何加密強度,不能拿來保護敏感資料。
str = "https://www.example.com";
len = str.length;
arr = [];
for(var i=0; i<len; i++){
arr.push(str.charCodeAt(i).toString(16));
}
console.log("x" + arr.join("x"));
charCodeAt(i) 取得該字元的 Unicode 編碼點,toString(16) 把它轉成十六進位字串,最後用 "x" 串接起來方便閱讀。
str = "x68x74x74x70x3ax2fx2fx77x77x77x2ex65x78x61x6dx70x6cx65x2ex63x6fx6d"; // 把這段字串貼到 Chrome 主控台或 Firebug 執行,即可看到原始內容
反過來的做法是以 "x" 切開字串,把每一段用 parseInt(hex, 16) 還原成數字,再用 String.fromCharCode() 組回字元:
var out = str.split("x").filter(function(s){ return s.length; })
.map(function(h){ return String.fromCharCode(parseInt(h, 16)); })
.join("");
console.log(out);
補充兩點:若字元超出 ASCII 範圍(例如中文),charCodeAt 會回傳四位以上的十六進位,切分時要留意;另外若目的只是安全傳輸,encodeURIComponent 或 Base64 會是更合適的選擇。