CasinoRoyale
CasinoRoyale

Reputation: 51

Using Javascript to format an HTML string to display properly

The back end hands off a string that gets displayed like:

"Hello, <br><br> This notice is to inform you that you are in violation of <font color=red><b>HR POLICY XXXXX</b></font>."

The point of this page is to let you easily copy-paste pre-generated emails, but spewing out a bunch of html tags through the sentences is unwanted.

The string in question is inside of a with an id of "textBlock".

The back end is Java with an Oracle DB. I can edit the java to some extent and I can't touch the DB at all. I've used the console to play around with the string and editing it in any way seems to make it display properly once I finish editing. The innerText includes tags like in my summary, the innerHTML displays the tags like <br>.

So far I've attempted to give the an onload attribute that calls a function named formatText(); that does: temp var = document.getElementById("textBlock").innerText; document.getElementById("textBlock").innerText = var;

as well as the above function with innerHTML instead of innerText. I've also tried using document.write(); but that clears the rest of the page.Finally I've added some random characters in front of the string and tried to use the replace("!@#","") function to replace those in an effort to mimic the "editing it in any way seems to make it display properly" that I noticed.

java

out.println("<td align=left id=textBlock onload=formatText();> !@#" + strTemp + "</td>" );

Expected:

Hello,

This notice is to inform you that you are in violation of HR POLICY XXXXX.

Actual:

Hello, <br><br> This notice is to inform you that you are in violation of <font color=red><b>HR POLICY XXXXX</b></font>.

Upvotes: 1

Views: 12131

Answers (2)

What you want, if I understood correctly, is some stripping html tags function. You can use regex

var str = "Hello, <br><br> This notice is to inform you that you are in violation of <font color=red><b>HR POLICY XXXXX</b></font>."

console.log(str)

var str2 = str.replace(/<[^>]*>?/gm, '')

console.log(str2)

If you want the html element to render your html, you need to use the DOM property innerHtml

var str = "Hello, <br><br> This notice is to inform you that you are in violation of <font color=red><b>HR POLICY XXXXX</b></font>."

document.getElementById('myDiv').innerHTML = str
<div id="myDiv">Hi</div>

Upvotes: 2

Pantalaimon
Pantalaimon

Reputation: 596

(resolved in comments, answer added for completeness)

When HTML tags are visible in the browser, it's usually encoded with html-entities, preventing it getting parsed as HTML. In this case a post-processing script was replacing the < and > characters to their entity counterparts &lt; and &gt;.

Disabling these replacements resolved the issue.

Upvotes: 1

Related Questions