2016-09-29 47 views
0

我看到一個代碼,並且該代碼有一個數組中的所有字符串..並且每個數組索引都是這樣的:「\ x31 \ x32 \ x33」等。編碼格式?;如何編碼 x31等字符串?

如果可能,那裏有一個在線編碼器?

+0

你能給出一個例子你字符串數組? –

+0

我需要這樣做:http://prntscr.com/cnmo88 – iZume

+0

在下面提供了一個答案:http://stackoverflow.com/a/39761829/1409180 – nikjohn

回答

0

如果您通過控制檯記錄字符串序列,就會得到解碼的字符串。因此,它是那樣簡單

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 
2

正如@nikjohn說,你可以解碼的字符串通過console.log

而我從question發現下面的代碼。我做了一些更改,輸出字符串將在\x48 \x65窗體中。

將字符串轉換成十六進制編碼,每個字符將用空格隔開。

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