JavaScript: convert String to Hex code

JavaScript is a powerful programming language that is widely used in web development. One of the common tasks in JavaScript programming is converting a string to a hexadecimal code. This can be done easily using a built-in function in JavaScript called charCodeAt(). In this article, we will discuss how to convert a string to a hexadecimal code using JavaScript and a simple function.

The function that we will use to convert a string to hexadecimal code is called the “hexEncoderFun”. This function takes a string as a parameter and returns the result in the form of hexadecimal code. Let’s look at the code for this function:

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

In the above function, we first declare a variable called "result" and initialize it to an empty string. Then, we loop through the characters in the input string using a "for" loop. Inside the loop, we use the "charCodeAt()" function to get the Unicode value of each character in the string. We then convert this Unicode value to a hexadecimal value using the "toString()" function with a base of 16. Finally, we concatenate this hexadecimal value to the "result" variable.

Once the loop is completed, we return the final value of the "result" variable, which contains the hexadecimal code for the input string.

Let's see an example of how to use this function:

var str = "Hello World!";
var hexCode = hexEncoderFun(str);

In the above example, we have declared a string variable called "str" and initialized it to "Hello World!". We then call the "hexEncoderFun()" function with the "str" variable as a parameter and assign the result to a variable called "hexCode". Finally, we print the "hexCode" variable to the console using the "console.log()" function.

When we run this code, we will get the hexadecimal code for the input string "Hello World!". The output will be:


As we can see, the output is a string of hexadecimal digits that represents the input string "Hello World!".

In conclusion, converting a string to a hexadecimal code in JavaScript is a simple task that can be accomplished using the built-in "charCodeAt()" and "toString()" functions. The "hexEncoderFun()" function that we discussed in this article provides a convenient way to convert a string to hexadecimal code using JavaScript.





Leave a Reply