Showing posts with label entities. Show all posts
Showing posts with label entities. Show all posts

Monday 14 April 2014

HTML Entities jQuery plugin for the code tag

Try presenting HTML in a web page. It's a pain in the neck. Even in between the code tag, you have to create HTML Entities for greater than and less than symbols etc.
Not wanting to go through that pain ever again, I have created a small JavaScript plugin which helps.
First, here is the HTML page important differences in red:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Convert to HTML Entities</title>  
  </head>
  <body>
    <code>Hello, <h1>world!</h1></code>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="htmlentities.plugin.js"></script>
    <script>
    (function()
    {
      $('code').htmlentities();
    })();
    </script>
  </body>
</html>
Now, htmlentities.plugin.js:
(function($)
{
  $.fn.htmlentities = function()
  {
 
    beforeString = $(this).html();  
    afterString = beforeString.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    $(this).html(afterString);
  }
})(jQuery);

Happy coding!