Home > Net >  How to use encoded HTML text within string literals?
How to use encoded HTML text within string literals?

Time:11-30

I am trying to include a HTML encoded special character within a string literal, but it will not render as HTML in the final document.

I am trying to do it like such:

const head = { 
title: `${ApplicationName} - ${Slogan}™`
}

In the above code the ™ part it supposed to render a trademark symbol like ™. But when this code makes it into the HTML document it ends up rendering as a string:

<head>
  <title>Imaginary Inc - We straight don't exist&trade;</title>
</head>

Is there any way to get it to work, maybe using some kind of escaping technique?

CodePudding user response:

You can use innerHTML or a DOM Parser with innerText

let t = document.querySelector('title');
let var1 = 'foo', var2 = 'bar'
let str = `${var1} - ${var2}&trade;`
t.innerHTML = str;
console.log(t)

let doc = new DOMParser().parseFromString(str, 'text/html');
t.innerText = doc.body.innerHTML;
console.log(t)
<title></title>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use the unicode of the character to achieve this, add a backslash before the character unicode to denote this in JavaScript. (\u2112)

const title = $("title");
title.append("\u2122");

console.log(title.text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
  <title>My Title</title>
</head>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related