How to use backticks inside a const?

Hi, I use workers to replace the of a page.

The new head code I store in a const and replace it with the HTML rewriter, like this:

const $head = `

`;

But the head contains inline JS code that uses backticks, which throws an error (Uncaught SyntaxError: Unexpected identifier at line 83 (Code: 10021))

const $head = `
  <head>
    <script> ...  `${e}-${o}` ...   </script>
  </head>
`;

class replaceHead {
  element(element) {
    element.replace(head, {html: true});
  }
}

I tried using multiple backticks and escaping with , but nothing works.
What would be the correct way to handle this?

If you don’t hear back here, you might try the Workers Discord server:

Heyo, you are closing the backticks and then trying to put a variable in

const $head = ` // << You open the backticks (string literal) here
  <head>
    <script> ...  `${e}-${o}` ...   </script> // <<< here you're closing it, then putting ${e}-${o} and then re-opening it. ${e} isn't valid in JS except in a string literal (which you closed)
  </head>
`;

Instead you can just do:

const head = ` // << You open the backticks (string literal) here
  <head>
    <script> ...  ${e}-${o} ...   </script>
  </head>
`;

Here, it is not being closed and re-opened. It’s just one big string literal

If you use an editor like VS Code you should see feedback on this saying it’s invalid and why
image

1 Like