javascriptfromcharcode

Why String.fromCharCode() does not work with variable as parameter?


I noticed that String.fromCharCode() does not work with a variable as parameter.

Here is some sample code:

var x = atob('ODAsNjUsODMsODMsODcsNzksODIsNjgsOTUsNDgsNDk=');
console.log('\''+x.replace(new RegExp(',', 'g'), '\',\'')+'\'');
console.log(String.fromCharCode('\'' + x.replace(new RegExp(',', 'g'), '\',\'') + '\''));

Now this would evaluate to

'80','65','83','83','87','79','82','68','95','48','49'

which is a correct parameter chain for String.fromCharCode()
because this works:

console.log(String.fromCharCode('80','65','83','83','87','79','82','68','95','48','49'));

Why doesn't it accept the variable as parameter?

Have I done something wrong here?


Solution

  • In:

    var x = atob('ODAsNjUsODMsODMsODcsNzksODIsNjgsOTUsNDgsNDk=');
    console.log(String.fromCharCode('\'' + x.replace(new RegExp(',', 'g'), '\',\'') + '\''));
    

    '\''+x.replace(new RegExp(',', 'g'), '\',\'')+'\'' produces a string. It’s just a text that says '80','65','83','83','87','79','82','68','95','48','49'. If you pass this string to String.fromCharCode... definitely not what you wanted. How is JavaScript supposed to convert this to one number?

    String.fromCharCode('80','65','83','83','87','79','82','68','95','48','49')
    

    Here you pass multiple arguments. Multiple strings. And each of them can easily be converted into a number.

    What you can do is simply split the string at , and then splat the resulting array: (ECMAScript 6)

    String.fromCharCode(...x.split(','));