-1

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?

Tom
  • 1,387
  • 3
  • 19
  • 30
iHasCodeForU
  • 179
  • 11

2 Answers2

2

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(','));
idmean
  • 14,540
  • 9
  • 54
  • 83
1

You could just pass an array tho:

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

Here is a similar.. the same question:

Can I pass an array into fromCharCode

Community
  • 1
  • 1
Lain
  • 3,657
  • 1
  • 20
  • 27