Q:

Dynamic Hexadecimal escape sequence

I'm converting a json to HEX and I want to concatenate with a \x
Example:
I have this ->
var myString = '"131';

And I want this ->
var HardCodeString = "\x22\x31\x33\x31" // console.log prints -> "131

When I make that string literal, it creates the four-byte string "131.
But when I create a loop to create this string out of dynamically-chosen hex values, like so
function ascii_to_hexa(str) {

    var arr1 = [];
    for (var n = 0, l = str.length; n < l; n ++) {
        var hex = "\\x" + Number(str.charCodeAt(n)).toString(16);
        arr1.push(hex);
    }
    return arr1.join('');
}

var newString = ascii_to_hexa('"131');

Look like work, but not!
If I add a console log to newString I can see:
'\x22\x31\x33\x31'

And if try to validate as the same happens
// should be equal, but not
if(HardCodeString == newString) {
// do something
}

A:

Hope this example help u
var hex = {
            "\"": '\x22',
            "{": '\x7B',
            "}": '\x7D',
            "A": '\x41',
            "B": '\x42',
            "C": '\x43',
            "D": '\x44',
            "0": '\x30',
            "1": '\x31',
            "3": '\x32',
            "2": '\x33'
        };

        function str_to_hex(str) {
            var res = '';
            for (var n = 0, l = str.length; n < l; n++) {
                res += hex[str[n]];
            }
            return res;
        }
        var str = '\"131';
        var res = str_to_hex(str);
        console.log(res); 

Please ask if any query.

