3

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

1
  • I tried this var something="text"; console.log(something.toString(16)), but it didn't work Commented Nov 25, 2015 at 15:26

2 Answers 2

6

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.

0

You can also use Buffer to convert ascii to hex

let hex = Buffer('Some Text', 'ascii').toString('hex');
console.log(hex);
1
  • 2
    There's no support for Buffer on browser-based JavaScript. If you try to run your code on browser's console, it will fail. Though original question didn't explicitly ask for browser or server based JS, having "jquery" on it may suggest that the solution was looking for, should work in a web browser. You should specify in your answer that this only will work on node.js to prevent confusion.
    – zedee
    Commented May 19, 2020 at 14:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.