简体   繁体   中英

how to convert string from ascii to hexadecimal in javascript or jquery

I want to convert string from ascii to hexadecimal

I tried:

var stringing = "";
jQuery.each("SomeText".split(""), function (i, data) {
    stringing = stringing + data.charCodeAt(0)
});

But this output is not the same as what I get at http://www.asciitohex.com/

I need to get the same values because only that works in KQL in sharepoint

How about

String.prototype.convertToHex = function (delim) {
    return this.split("").map(function(c) {
        return ("0" + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(delim || "");
};

and

"SomeText".convertToHex();
// -> "536f6d6554657874"

"SomeText".convertToHex(" ");
// -> "53 6f 6d 65 54 65 78 74"

Note that this will fail with Unicode characters. Use it for ASCII/ANSI input only.

You can also use Buffer to convert ascii to hex

let hex = Buffer('Some Text', 'ascii').toString('hex');
console.log(hex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM