; 如何编码像 \x31 等字符串?

;How encode string like \x31, etc?

我看到一段代码,该代码的所有字符串都在一个数组中。每个数组索引如下:“\x31\x32\x33”,等等。

我如何将 "hello" 转换为该编码格式?

如果可以的话,有在线编码器吗?

是十六进制编码。

www.unphp.net

http://ddecode.com/hexdecoder/

http://string-functions.com/hex-string.aspx

是少数几个可以使用十六进制编码为您提供编码和解码的网站。

如果您控制台记录字符串序列,您将获得解码后的字符串。所以就这么简单

console.log('\x31\x32\x33'); // 123

为了编码所述字符串,您可以扩展 String prototype:

String.prototype.hexEncode = function(){
var hex, i;

var result = "";
 for (i=0; i<this.length; i++) {
    hex = this.charCodeAt(i).toString(16);
    result += ("\x"+hex).slice(-4);
 }
 return result
}

现在,

var a = 'hello';
a.hexEncode(); //\x68\x65\x6c\x6c\x6f

正如@nikjohn 所说,您可以通过 console.log.

解码字符串

以及我从这个 question 中找到的以下代码。我做了一些更改,输出字符串将采用 \x48 \x65 形式。

它将字符串转换为十六进制编码,每个字符将由 space:

分隔
String.prototype.hexEncode = function(){
    var hex, i;

    var result = "";
    for (i=0; i<this.length; i++) {
        hex = this.charCodeAt(i).toString(16);
        result += ("\x"+hex).slice(-4) + " ";
    }

    return result;
};

var str = "Hello";
console.log(str.hexEncode());

以上代码的结果为\x48 \x65 \x6c \x6c \x6f