4

Here's my code:

let padded = "03";
ascii = `\u00${padded}`;

However, I receive Bad character escape sequence from Babel. I'm trying to end up with:

\u0003

in the ascii variable. What am I doing wrong?

EDIT:

Ended up with ascii = (eval('"\\u00' + padded + '"'));

2
  • 1
    Uh? The eval solution yields the same result asString.fromCodePoint... Nov 23, 2015 at 15:58
  • Don't provide your own answer in the question. If you think you have the answer, then post it as an answer.
    – user663031
    Nov 23, 2015 at 16:03

1 Answer 1

5

What am I doing wrong?

A unicode escape sequence is basically atomic. You cannot really build one dynamically. Template literals basically perform string concatenation, so your code is equivalent to

'\00' + padded

It should be obvious now why you get that error. If you want to get the corresponding unicode character you can instead use String.fromCodePoint or String.fromCharCode:

String.fromCodePoint(3)

If you want a string that literally contains the character sequence \u0003, then you just need to escape the escape character to produce a literal backslash:

`\\u00${padded}`
11
  • Oh I see! "You cannot really build one dynamically" is this not really a thing then? Is there no way of doing it? Nov 23, 2015 at 15:00
  • 2
    I guess you are looking for String.fromCodePoint: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… or alternatively (ES5): developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . Nov 23, 2015 at 15:03
  • 2
    Wait, you literally want a string "\u0003"? Why not ascii = `\\u00${padded}`; then? Because as Felix points out, String.fromCodePoint(0x404) === "\u0404" Nov 23, 2015 at 15:50
  • 1
    @benhowdle89 I think you may be confusing the escape sequence `\\` for two characters. It's not, it's just one. Here's an example Nov 23, 2015 at 16:05
  • 1
    @benhowdle89: It seems you are confusing something here. If you want the string value to literally consist of a \ followed by a u, followed by a 0, etc, then you need to escape the \ just like RGraham said. If you want a string that contains the character that is represented by the escape sequence "\u0003", then you can use fromCodePoint. Lets simplify: Take the escape sequence "\n", which represents a line break. Do you want a string that contains a line break or do you want a string that contains \ followed by n? Nov 23, 2015 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.