Showing posts with label encode. Show all posts
Showing posts with label encode. 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">
    <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>  
    <code>Hello, <h1>world!</h1></code>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src=""></script>
    <script src="htmlentities.plugin.js"></script>
Now, htmlentities.plugin.js:
  $.fn.htmlentities = function()
    beforeString = $(this).html();  
    afterString = beforeString.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

Happy coding!