Kieran Kieran - 15 days ago 5x
HTML Question

Javascript find and replace

I have made a small code generator for my team

It's very simple, you just fill out the fields & it effectively does a find and replace in the DIV below and shows what the new code should be. That's great!

The problem I have is that in order to get the code showing as clear text on the screen, I had to replace all the special characters with the below (e.g. &lt)

enter image description here

When manually copying and pasting, this is not a problem. However, I have a button that copies the contents of the DIV and exports to a .html file.

This then does not execute the code, because it copies the actual contents (including the lack of special characters).

Is there any way to get this code to run when I export? Is there a simple function to switch it back to be the original code before exporting?

The code generator is effectively lots of finds and replaces to enter user defined variables, it is below:

[code]function findMyText2(needle2, replacement2) {
if (haystackText.length == 0) {
haystackText = document.getElementById("haystack").innerHTML;
var match = new RegExp(needle2, "ig");
var replaced = "";
if (replacement2.length > 0) {
replaced = haystackText.replace(match, replacement2);

else {
var boldText = "<div style=\"background-color: yellow; display: inline; font-weight: bold;\">" + needle2 + "</div>";
replaced = haystackText.replace(match, boldText);
document.getElementById("haystack").innerHTML = replaced;
haystackText = document.getElementById("haystack").innerHTML;

The full code to be edited is:
enter image description here

Thank you in advance.


From what I understood of the problem, you basically need to unescape the contents of the div. Here is how you can do it.


<div style="display:none" id="dummy"></div>


var decoded = $("#dummy").html(encoded).text();

This code sets the internal HTML of the "dummy" div as encoded, which makes jquery decode it. Then text() simply returns the decoded code.

For more info see here - Javascript decoding html entities