Search code examples
node.jsecmascript-6escapingread-eval-print-looptemplate-literals

How do I put a single backslash into an ES6 template literal's output?


I'm struggling to get an ES6 template literal to produce a single backslash it its result.

> `\s`
's'
> `\\s`
'\\s'
> `\\\s`
'\\s'
> `\\\\s`
'\\\\s'
> `\u005Cs`
'\\s'

Tested with Node 8.9.1 and 10.0.0 by inspecting the value at a Node REPL (rather than printing it using console.log)


Solution

  • If I get your question right, how about \\?

    I tried using $ node -i and run

    console.log(`\\`);
    

    Which successfully output a backslash. Keep in mind that the output might be escaped as well, so the only way to know you are successfully getting a backslash is getting the character code:

    const myBackslash = `\\`;
    console.log(myBackslash.charCodeAt(0)); // 92
    

    And to make sure you are not actually getting \\ (i.e. a double-backslash), check the length:

    console.log(myBackslash.length); // 1