Converting ASCII to hexadecimal in JavaScript


We are required to write a JavaScript function that takes in a string that represents a ASCII number. The function should convert the number into its corresponding hexadecimal code and return the hexadecimal.

For example −

f the input ASCII string is −

const str = '159';

Then the hexadecimal code for this should be 313539.

Example

Following is the code −

const str = '159';
const convertToHexa = (str = '') =>{
   const res = [];
   const { length: len } = str;
   for (let n = 0, l = len; n < l; n ++) {
      const hex = Number(str.charCodeAt(n)).toString(16);
      res.push(hex);
   };
   return res.join('');
}
console.log(convertToHexa('159'));

Output

Following is the output on console −

313539

Updated on: 11-Dec-2020

529 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements