0

I want to display Java source code in an html site.

When I escape all > and < before pasting the code into the html, it obviously works, everything is displayed correctly.

When I don't, a HashMap is displayed like this:

HashMapclass="string">"">> map = new HashMap<>();

which should be

HashMap<String, ArrayList<String>> map = new HashMap<>();

When I use JQuery's text() method and print the result to the console, I get this:

HashMap> map = new HashMap<>();

And when I use the html() method, I get this:

HashMap<string, arraylist<string="">&gt; map = new HashMap&lt;&gt;();

How should I retrieve the text from the code-Element so that I can correctly escape > and

Doing the same thing with XML source code works. I use

$(this).html()

to get the text in the code-Element and then escape the characters. The XML is then displayed with tags instead of just text.

user3813234
  • 1,580
  • 1
  • 29
  • 44

1 Answers1

1

if you insert into your html a line like:

<code id="okai">HashMap<String, ArrayList<String>> map = new HashMap<>();</code>

You have to understand that HTML will consider the "<String" as the beginning of a new tag and because there is no corresponding end tag (i.e.: </String>) the html code is rendered in:

HashMap> map = new HashMap<>();

If you take a look with the development tool (press F12 in chrome) you will appreciate what i intend: in the code tag you have now two tags: a string and another wrong tag.

The same problem happens if you write a </script> tag inside a script (please refer to: http://stackoverflow.com/questions/236073/why-split-the-script-tag-when-writing-it-with-document-write).

So there is no need to proceed with the text or html jquery functions because the imput html has been just changed by the html interpreter.

To insert a java source inside your html page I prefer a way like:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="jquery-ui.css">
    <script src="jquery-1.11.2.js"></script>
    <script src="jquery-ui.js"></script>
    <script type="application/javascript">
        $(function() {
            var newTxt = $('#myCodeId').html().replace('<!--', '').replace('-->', '');
            $('#myCodeId').text(newTxt);
        });
    </script>
</head>
<body>
<code id="myCodeId"><!--HashMap<String, ArrayList<String>> map = new HashMap<>();--></code>
</body>
</html>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61