Syed
Syed

Reputation: 16513

How to convert number to character using 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

Upvotes: 18

Views: 48580

Answers (6)

Adrian
Adrian

Reputation: 8597

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.

Upvotes: 12

user8897421
user8897421

Reputation:

For uppercase, 97 was the wrong offset, and it didn't give you the desired result with 0 being J.

360 to CFJ

230 to BCJ

function convert(n) {
  return String.fromCharCode(
   ...n.toString().split("").map(c => (+c||10) + 0x40)
  );
}

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

function onInput(elm){
  console.clear()
  console.log( convert(elm.value) )
}
<input oninput="onInput(this)">


And you can do this without the initial string conversion.

function convert(n) {
  var a = Array(Math.floor(Math.log10(n))+1);
  var i = a.length;
  while (n) {
    a[--i] = ((n%10)||10) + 0x40;
    n = Math.floor(n/10);
  }
  return String.fromCharCode(...a);
}

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

Upvotes: 1

Slai
Slai

Reputation: 22876

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

console.log( String.fromCharCode(...[...1234567890 + ''].map(c => (+c || 10) | 64)) )

Upvotes: 3

Jecfish
Jecfish

Reputation: 4189

Option 1: map it

const from = 1234567890;

const answer = from
  .toString() // convert to string, ignore this if it's already a string
  .split('') // split to array
  .map(x => +x + 97) // convert to char code number
  .map(String.fromCharCode) // convert to char code
  .join(''); // convert back to string

console.log(answer)

Option 2: pass in multiple params

const from = 1234567890;

const fromCharCodes = from
  .toString() // convert to string, ignore this if it's already a string
  .split('') // split to array
  .map(x => +x + 97) // convert to char code number

const answer = String.fromCharCode(...fromCharCodes);

console.log(answer);

Upvotes: 0

JLRishe
JLRishe

Reputation: 101680

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>

Upvotes: 18

CRice
CRice

Reputation: 32176

You'll need to define your alphabet up front. For your snippet, you seem to want 1-9 to map to A-I, and 0 to J, so:

const alphabet = "JABCDEFGHI";

Then it's just a matter of using each digit of the number as an index in that alphabet:

function numberToString(num) {
    // Split out each digit of the number:
    const digits = Math.floor(num).toString().split("").map(Number);

    // Then create a new string using the alphabet:
    return digits.reduce((str, digit) => {
        return str + alphabet[digit];
    }, "");
}

That should satisfy your constraints. Here's an example of this in action:

const alphabet = "JABCDEFGHI";

function numberToString(num) {
    // Split out each digit of the number:
    const digits = Math.floor(num).toString().split("").map(Number);

    // Then create a new string using the alphabet:
    return digits.reduce((str, digit) => {
        return str + alphabet[digit];
    }, "");
}

console.log(numberToString(360)) // CFJ
console.log(numberToString(230)) // BCJ

Upvotes: 1

Related Questions