1

I have the following bit of JS code being executed in a ASP.CORE View which is intended to basically set the content of an element on the page.

if (notificationBanner) {
    var bannerText = unescape("@ViewData.GetClient().GetText("$.resetCredentials.step2.otpSendBanner")");
    console.log(bannerText);
    notificationBanner.innerHTML = bannerText;
}

The following is being logged in browser console:

<p>A One Time Password (OTP) has been sent to your mobile number below. Enter the OTP in the field below. <strong>The OTP is valid for 10 minutes</strong>.</p>


And the element ends up like this:

enter image description here

However this is not correct, I want the part in <strong></strong> to be bold. Why is it adding it as text?

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33
Emcrank
  • 310
  • 2
  • 12
  • Because character entities are used similar in principle to escaping something so that you output the literal symbol instead of have the browser treat it as something to render. If you want it to actually render, use `<` instead of `<` etc. – CrayonViolent Oct 01 '19 at 18:59
  • I'm not sure I fully understand? Is there any method that will convert them into < and > I thought that was the purpose of unescape()? – Emcrank Oct 01 '19 at 19:05
  • `unescape()` is for url components. AFAIK there is no built in js method for this. Where is the value coming from? If you are outputting via serverside script, a lot of server-side languages have functions for decoding it. Or you can see e.g. https://stackoverflow.com/questions/5796718/html-entity-decode for js solutions. – CrayonViolent Oct 01 '19 at 19:08

1 Answers1

0

I was looking for a vanilla JS solution so looking at the post crayon provided. Found a good solution. Thanks for your help.

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

if (notificationBanner) {
    var bannerText = unescape("@ViewData.GetClient().GetText("$.resetCredentials.step2.otpSendBanner")");
    console.log(bannerText);
    notificationBanner.innerHTML = decodeHtml(bannerText);
}
Emcrank
  • 310
  • 2
  • 12