Convert number to characters in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have a login system where users are required to provide a unique userID to uniquely identify them. And for obvious security reasons, we want to obfuscate the userID so that it is fairly hard to guess the number.

Basically, we are required to write two functions.

  • encode(),

  • decode()

The first function should convert our number input into a base 26 alphabet mapping. And the second function should convert the alphabet mapping back into the original number.

Although this isn't very practical as most of the Hashing algorithms do not provide to and fro conversions, but for the purpose of this question, we are not considering that.

For example − If the number is 31, then,

encode(31) = 'ea'
and, decode('ea') = 31


The code for this will be −

const num = 31;
const encode = num => {
   let res = '';
   const legend = 'zabcdefghijklmnopqrstuvwxy';
      const rem = num % (legend.length);
      res += legend[rem];
      num = (Math.floor(num / legend.length));
   return res;
const decode = str => {
   let num = 0;
   const legend = 'zabcdefghijklmnopqrstuvwxy';
   for(let i = 0; i < str.length; i++){
      const ind = legend.indexOf(str[i]);
      num += (ind * Math.pow(legend.length, i));
   return num;


And the output in the console will be −

Published on 23-Nov-2020 14:28:26