Does JavaScript support verbatim strings?

No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes.

I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue was that developers could enter anything in the Page.Alert() method.

What I did to solve this was as follows:

public void Alert(string message)
{
    message = message.Replace("\\", "\\\\")
        .Replace("\r\n", "\n")
        .Replace("\n", "\\n")
        .Replace("\t", "\\t")
        .Replace("\"", "\\\"");

    // and now register my JavaScript with this safe string.
}

Just use String.raw()

String.raw`\n`

will output

\\n

But I don't know how to solve the case:

String.raw`hello`hello`  // It will throw an TypeError
String.raw`hello\`hello` // Output is 'hello\\`hello'

I don't know how to deal with ` :(


Template strings do support line breaks.

`so you can
do this if you want`

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

It does not of course prevent expansion from occurring the in the text, and by extension, code execution but maybe that's a good thing?

Note: I don't think there's a way to take an existing string and run it through expression interpolation. This makes it impossible to inject code this way since the code has to originate in the source. I don't know of an API that can do expression interpolation on-demand.

Note 2: Template strings are a ES2015 / ES6 feature. Support in every browser except (wait for it...) IE! However, Edge does support template strings.

Note 3: Template strings expand escape sequences, if you have a string inside a string that string will expand its escape sequences.

`"A\nB"`

...will result in:

"A
B"

...which will not work with JSON.parse because there's now a new-line in the string literal. Might be good to know.