Converting to hex and summing the numeral part in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string. Our function should convert every character of the string to the hex value of its ascii code, then the result should be the sum of the numbers in the hex strings ignoring the letters present in hex.

Example

Following is the code −

 Live Demo

const str = "Hello, World!";
const toHexAndSum = (str = '') => {
   return str
   .split('')
   .map(c=>c.charCodeAt())
   .map(n=>n.toString(16))
   .join('')
   .split('')
   .filter(c=>'123456789'.includes(c))
   .map(d=>parseInt(d))
   .reduce((a, b)=>a+b, 0)
};
console.log(toHexAndSum(str));

Output

Following is the console output −

91
raja
Published on 17-Apr-2021 10:48:54
Advertisements