3

My code is:

let testStr = "Asdfads";
let htmlStr = `<script>${ testStr }</script>`; // but it works with: <div>${ testStr }</div>
console.log(htmlStr);

It returns me an error:

Uncaught SyntaxError: Unterminated template literal

What do I do wrong? I run it on the latest Chrome.

7
  • 1
    It works for me. Commented Feb 8, 2018 at 14:49
  • @user202729, it doesn't work in the snippet also! I'm using MacOS X 10.12 Commented Feb 8, 2018 at 14:52
  • issue is closing tag <\/script> Commented Feb 8, 2018 at 14:53
  • @epascarello So, template literal is actually a modern document.write ..? Commented Feb 8, 2018 at 14:55
  • @Teemu Has nothing to do with document.write..... A normal string would have the same issue. Commented Feb 8, 2018 at 14:55

2 Answers 2

3

The problem is with your "</script>": it ends the script element in which it is embedded (hence the "unterminated template literal").

A solution is to write it in another form, for example

`</` + "script>"

or

let htmlStr = `<script>${ testStr }</${"script"}>`;

or

let htmlStr = `<script>${ testStr }</\script>`;

(any other construct not containing "</script>" would be fine).

This isn't about templates or strings: this is read when the HTML page is read, long before the javascript is even parsed.

Sign up to request clarification or add additional context in comments.

7 Comments

But why does it work with the: <div>${ testStr }</div>? It's also unescaped.
Because HTML tags need to be matched.
@JavaRunner the problem is only with </script> because that's what tells the page parser where the script ends, before the script is event parsed.
So why not give a solution for a template literal instead of telling them they have to use ""?
@epascarello because it's painful to write template literals in SO answers... But I'll try
|
0

Closing script tags should be escaped.

let htmlStr = `<script>${ testStr }<\/script>`;

would work

2 Comments

Not really. Just the </script> because it is read before he Javascript is even parsed.
Yeah, I did mean to say closing script tags. Good spot. I see you answered just before me anyway so they have the answer.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.