2

I have some code like this:

str = ""
for (var i = 0; i < 5; i++) str += eval("'\\u" + Math.floor(Math.random() * 65536).toString(16) + "'")

Occasionally when this is ran in a console, an Uncaught SyntaxError: Invalid Unicode escape sequence occurs. The error is in the evaluation. The syntax, including the eval, should work. A string with a backslash, a "u", and 4 random hex digits is passed into the eval. The eval interprets the "\u" and the hex digits as an Unicode character. Somehow, the error appears with that good (enough) syntax. Please find a the reason behind this error, and present a version of this code that circumvents this error.

  • 1
    How do you know there are 4 hex characters? – Pointy Mar 17 '19 at 02:03
  • 1
    Also, when you do that, it's possible to create non-valid UTF-16 code points. – Pointy Mar 17 '19 at 02:04
  • Have you tried printing the string before evaluating it, to see what the bad strings are? Also, instead of random, check all values from 0 to 65535. When you see what the invald strings are, you might get some ideas – Vilx- Mar 17 '19 at 02:05
  • @Pointy In the `Math.floor(Math.random() * 65536)` the 65536 is 16 (the number of digits in hex) ^ 4 (hex digits). –  Mar 17 '19 at 02:06
  • @Vilx- When I tried printing the individual strings given to `eval`, the errors were caused by a missing hex digit in the "Unicode escape sequence". I think a zero in a hex digit had been represented by an empty string by the `.toString(16)`. –  Mar 17 '19 at 02:14
  • Yes but not all 16-bit values are valid UTF-16 codes. – Pointy Mar 17 '19 at 02:15
  • Yes, `5.toString(16)` will return `"5"`, not `"0005"`. – Vilx- Mar 17 '19 at 13:48
  • @Vilx- Can you fix this part somehow? –  Mar 26 '19 at 21:36
  • Well, frankly, I think you should be able to figure this out yourself, but, ok - here you go: `5.toString(16).padStart(4,"0")` – Vilx- Mar 26 '19 at 22:07
  • 1
    Shouldn't that be in the answer section? –  Mar 26 '19 at 22:17

0 Answers0