Question

I'm building a small application that will take user HTML input and convert it into a human-readable format for a PHP email.

Example
Input:

<html>
  <a href="file.ext">file</a>
</html>

and I want that to come out as (in text format):

<?php
  $message = "<html>"
  . "<a href='file.ext'>file</a>"
  . "</html>";
?>

I've got the syntax and all that working, but my problem is the HTML tags. Even when I've supposedly encoded them (\x3C, \x3E), they still display as HTML - so I get the link instead of text output. I've also tried &gt; and &lt;. The quotes (\x22/\x27) work.

My JS (using jQuery):

function convert() {
$("#result").html("&lt;?php<br/>$message = ");
var text = $("#html").val();
text = text.split("\n");
$("#html").val("");
for(var i=0; i<text.length; i++) {
    text[i].replace("'","\x27");
    text[i].replace('"',"\x27");
    text[i].replace("<","\x3C");
    text[i].replace(">","\x3E");
    if(i<(text.length-1)) {
        if(i==0) {
            var line = "\x22"+text[i]+"\x22";
            $("#result").append(line+"<br/>");
        }
        else {
            var line = ". \x22"+text[i]+"\x22";
            $("#result").append(line+"<br/>");
        }
    }
    else {
        var line = ". \x22"+text[i]+"\x22";
        $("#result").append(line+";<br/>?>");
    }
}
}

Does anyone know why this doesn't work?

Was it helpful?

Solution

It might be because because you're using "append" which will take in an HTML string as a parameter and add it as an element to the DOM.

Have you tried replacing append() with text()? I tried using an HTML string with the text method and it worked fine on my end.

Notice the difference when using those two methods:

var line = '<a href="#">foobar</a>';

// string
$('#result').text(line+"<br/>");

// OR string with the element's prior text value
var str = $('#result').text();
$('#result').text(str + line + "<br/>");

// element
$('#result').append(line+"<br/>");

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top