Subscribe For Free Updates!

We'll not spam mate! We promise.

Aug 14, 2014

htmlentities() and html_entity_decode() in JQuery

htmlentities() and html_entity_decode() in JQuery :

htmlentities() and html_entity_decode() in JQuery
We are all know about use of htmlentities() in PHP. This function is used to convert all character to HTML entities. both function are used to treat string as a html and HTML as a string.
  
    For Example :
  
              
            echo htmlentities("TechniqZone");
          
         ?>

      
        Output :
      
            &lt ;a href=&#39 ;techniqzone.blogspot.in'&#39 ;&gt ;TechniqZone&lt ;/a&gt ; 
 // here semicolons (;) are placed with spaces for display here.
           
        This is very usefull in many places in php files to display html tags in website. But in javascript/JQuery, pre-defined encode decode function is not available.
      
        I hereby explained how to use encode and decode of HTML tags in JQuery. Before that need to know the diifference between JQuery.html() and JQuery.text().
      
            JQuery.html() - Treat string as HTML.
            JQuery.html() - Treat HTML as string.

          
        For Example :
      
            $("#techZone").html("<a href=''></a>");
            $("#techZone").text("<a href=''></a>");


Okay, now we create encode/decode custom function using JQuery.
  
        function htmlentities(str)
        {
            if(str) // check str is empty or not.
                return $("<div />").text(str).html();
            else
                return 'Argument mis-matched';
        }

      
        htmlentities("TechniqZone");
      
     Here create dummy <div> tag and append given string as text, after that take that dummy div text as html content.
  
     For decode,
  
        function html_entity_decode(str)
        {
            if(str) // check str is empty or not.
                return $("<div />").html(str).text();
            else
                return 'Argument mis-matched';
        }

  
        html_entity_decode("&lt ;a href=&#39 ;techniqzone.blogspot.in&#39 ;&gt ;TechniqZone&lt ;/a&gt ;");
// here semicolons (;) are placed with spaces for display here.

Note : htmlentities and html_entity_decode function are only working with jquery plugin files.

TechniqZone Socializer Widget
SOCIALIZE IT →
FOLLOW US →
SHARE IT →

0 comments:

Post a Comment