How to convert a string to hex on the server side

BoHyun Jung
Mega Sage

How do I convert string to hex in server side script?

3 REPLIES 3

Pratiksha2
Mega Sage

Hello @BoHyun Jung 

Please try below line of code in your server side script:

var originalString = "Hello, World!";

// Convert string to hexadecimal
var hexString = '';
for (var i = 0; i < originalString.length; i++) {
    hexString += originalString.charCodeAt(i).toString(16);
}

// Output hexadecimal representation
gs.info("Hexadecimal representation: " + hexString);

Please Mark Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.

 

Thanks,

Pratiksha

AshishKM
Kilo Patron
Kilo Patron

Hi @BoHyun Jung , 

You can apply toString(16) method to each character of the string value.

 

 

var inputString = "Welcome to ServiceNow";
var hexString = "";
for (var i = 0; i < inputString.length; i++) {
    var charCode = inputString.charCodeAt(i);
    // Convert character code to hexadecimal
	hexString += charCode.toString(16); 
}
gs.info("Hex ->" + hexString);

 

 

Source: https://stackoverflow.com/questions/18626844/convert-a-large-integer-to-a-hex-string-in-javascript

 

-Thanks,

AshishKM


Please mark this response as correct and helpful if it helps you can mark more that one reply as accepted solution

Amit Verma
Kilo Patron
Kilo Patron

Hi @BoHyun Jung 

 

You can try with the below function :

 

function toHex(str) {
    var result = '';
    for (var i=0; i<str.length; i++) {
      result += str.charCodeAt(i).toString(16);
    }
    return result;
  }

toHex('sample string');

 

Thanks & Regards

Amit Verma


Please mark this response as correct and helpful if it assisted you with your question.