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
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>
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.
console.log( (1234567890 + '').replace(/\d/g, c => 'JABCDEFGHI'[c] ) )
console.log( String.fromCharCode(...[...1234567890 + ''].map(c => (+c || 10) | 64)) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With