MeTe-30
MeTe-30

Reputation: 2542

JavaScript Array join() cause null (%00) character in result

I'm trying to put watermark in js file requests through RequireJs:

requirejs.config({
    baseUrl: '/app',
    urlArgs:  [98, 121, 65, 68, 77].map(String.fromCharCode).join('')+'&v=1.0.0'
});

For some reasons i cannot put byADM directly, so i wrote above code.
My problem is after joining characters it shows b%00%00y%01%00A%02%00D%03%00M%04%00&v=1.0.0 instead of byADM&v=1.0.0 in the url. it's look like '' convert to %00.
What can i do to get ride of this?
Is there any real empty character in String library or something else ?

Upvotes: 1

Views: 355

Answers (2)

deceze
deceze

Reputation: 522135

Array.prototype.map passes three arguments to the callback: currentValue, index, array. String.fromCharCode accepts any number of arguments, converting them all in one go. Essentially you are calling String.fromCharCode(98, 0, []) by passing String.fromCharCode directly as callback to map.

You'll need to cull the additional arguments:

[98, 121, 65, 68, 77].map((c) => String.fromCharCode(c))

But, rather than fighting this behaviour, you can also use String.fromCharCode's ability to accept any number of arguments to simplify your code:

String.fromCharCode.apply(String, [98, 121, 65, 68, 77]) + '&v=1.0.0'

Or, you know…

String.fromCharCode(98, 121, 65, 68, 77) + '&v=1.0.0'

Upvotes: 2

C3roe
C3roe

Reputation: 96316

I don’t know why exactly, but it looks like you need to wrap String.formCharCode into an additional anonymous function:

urlArgs:  [98, 121, 65, 68, 77].map(
  function(c) {
    return String.fromCharCode(c);
  }
).join('')+'&v=1.0.0'

Upvotes: 2

Related Questions