Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert number to character using javascript?

Tags:

javascript

How to convert 1234567890 = ABCDEFGHIJ, For eg. 360 to CFJ

I know how to do it for single character:

var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...

but not sure how can I do it for multiple/group of number at once: For eg. 230 to BCJ

like image 445
Syed Avatar asked Jan 20 '18 02:01

Syed


3 Answers

This would work:

function convert(num) {
    return num
        .toString()    // convert number to string
        .split('')     // convert string to array of characters
        .map(Number)   // parse characters as numbers
        .map(n => (n || 10) + 64)   // convert to char code, correcting for J
        .map(c => String.fromCharCode(c))   // convert char codes to strings
        .join('');     // join values together
}

console.log(convert(360));
console.log(convert(230));

And just for fun, here's a version using Ramda:

const digitStrToChar = R.pipe(
    Number,                      // convert digit to number
    R.or(R.__, 10),              // correct for J
    R.add(64),                   // add 64
    R.unary(String.fromCharCode) // convert char code to letter
);

const convert = R.pipe(
   R.toString,            // convert number to string
   R.split(''),           // split digits into array
   R.map(digitStrToChar), // convert digit strings to letters
   R.join('')             // combine letters
);

console.log(convert(360));
console.log(convert(230));
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
like image 132
JLRishe Avatar answered Nov 20 '22 21:11

JLRishe


The fromCharCode accepts a list of arguments as parameter.

String.fromCharCode(72, 69, 76, 76, 79); for example will print 'HELLO'.

Your example data is invalid though. The letter 'A' for example is 65. You'll need to create a comma separated argument that you feed into the function. If you don't provide it as a comma separated arg, you'll be trying to parse a single key code which will most likely fail.

like image 9
Adrian Avatar answered Nov 20 '22 22:11

Adrian


console.log( (1234567890 + '').replace(/\d/g, c => 'JABCDEFGHI'[c] ) )

console.log( String.fromCharCode(...[...1234567890 + ''].map(c => (+c || 10) | 64)) )
like image 3
Slai Avatar answered Nov 20 '22 21:11

Slai