Hi Guys,
Here is a quick tip if you would like to convert a string into a sum of ASCII codes for all characters
Function you can use
For ES5:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var Util = { stringToASCIISum:function(value){ return value .split('') .map(function (char) { return char.charCodeAt(0); }) .reduce(function (curr, prev) { return prev + curr; }); } } // USAGE console.log(Util.stringToASCIISum("YourString")); // outputs 1062 |
We can do equivalent in ES6 in
1 2 3 |
[...'YourString'] .map(char => char.charCodeAt(0)) .reduce((curr, prev) => prev + curr) |
There are times when you would need to know the integer value of the string, be it in sorting or any other scenario, this function will help you out. If this code can be improved. please do let me know, I hope this helps,
Leave a Reply