Using Google Prettify to display HTML
Asked Answered
P

2

8

for Google Prettify to display HTML code sample properly, you should replace all the < with &lt; and all the > with &gt;.

How do you automate that process using JavaScript only ?

Palatable answered 4/5, 2012 at 2:29 Comment(0)
D
21

If you put your code inside an <xmp> element, you don't need to escape HTML special characters as shown in the tests

 <h1>HTML using XMP</h1>
 <xmp class="prettyprint" id="htmlXmp"
 ><html>
   <head>
     <title>Fibonacci number</title>
   </head>
   <body>
     <noscript>
       <dl>
         <dt>Fibonacci numbers</dt>
         <dd>1</dd>
         <dd>1</dd>
         <dd>2</dd>
         <dd>3</dd>
         <dd>5</dd>
         <dd>8</dd>
         &hellip;
       </dl>
     </noscript>

     <script type="text/javascript"><!--
 function fib(n) {
   var a = 1, b = 1;
   var tmp;
   while (--n >= 0) {
     tmp = a;
     a += b;
     b = tmp;
   }
   return a;
 }

 document.writeln(fib(10));
 // -->
     </script>
   </body>
 </html>
 </xmp>
Docia answered 4/5, 2012 at 2:38 Comment(5)
@Brett, it'll work as long as the HTML you're prettifying doesn't contain the string "</xmp".Docia
I even didn't know such the tag exists oOMaggiemaggio
problem: xmp is obsolete, and vertical extra space appears.Bodhisattva
Had some issues with bootstrap styling overwriting prettify. Solved by surrounding with <pre><xmp class="prettyprint lang-html"> ... </xmp></pre>Nalepka
<xmp> HTML tag is now obselete.Painting
N
1

You could do a global replace to the content using a RegEx.

var regex = new RegExp("<", "g");
console.log(content.replace(regex, "&lt;"));
Narrow answered 4/5, 2012 at 2:37 Comment(1)
You need to properly escape ampersands as well.Docia

© 2022 - 2024 — McMap. All rights reserved.