简体   繁体   中英

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 .

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>.

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>

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM