HTML_Entity_convertor

convert named entities into numeric and vice versa

by lid0

HTML

<span>Input</span>
<div id="_doc" style='background-color:#ececec'>
    
<!-- untouched -->
<p >&amp;aleph;&amp;infin;</p>
<p>&amp;#8501; &amp;#8734; </p>
</div>

<hr>
  <span>Output</span>
<div id="doc" style="background-color:#cfcfcf">
      
    <!-- change named to numeric and numeric to named -->
<p >&amp;aleph;&amp;infin;</p>
<p>&amp;#8501; &amp;#8734;</p>
</div>

    <div>Convert Name to Numeric </div>
<textarea id="wmd-input">
    &amp;aleph;
    &amp;infin;
</textarea>
<button id="fix_btn">Encode</button>
<textarea id="output"></textarea>

CSS

textarea {
    width:500px;
    height:150px
}
button{
    display:block;
}
span{
    font-size:12px;
}

JavaScript

function replace_named_ent_with_code_ent(a,b,c){
     var extend_ent = {
                    "aleph":"8501",
                    "infin":"8734",
                    "otimes":"8855",
                    "radic":"8730",
                   }
      if (extend_ent.hasOwnProperty (c) ){
        return "&#" + extend_ent[c] +";"
      } else {
        return a
      }
    
}

function replace_code_ent_with_named_ent(a,b,c){
       var extend_ent = {
                    "8501":"aleph",
                    "8734":"infin",
                    "8855":"otimes",
                    "8730":"radic",
                   }
      if (extend_ent.hasOwnProperty (c) ){
        return "&" + extend_ent[c] +";"
      } else {
        return a
      }

}


$("div#doc p").each (function (a,elm){
    var $elm = $(elm);
    $elm.html( $elm.html().replace(/(&amp;)([A-z]+);/g,replace_named_ent_with_code_ent));
    
    $elm.html ( $elm.html().replace(/(&amp;#)([0-9]+);/gm,replace_code_ent_with_named_ent));
    
});



$("#fix_btn").click(function (){
    
    //fix input where & was already encoded as &amp;
    $("#output").val( $("#wmd-input").val().replace(/(&amp;)([A-z]+);/g,replace_named_ent_with_code_ent));
    
    //fix raw input & is literal 
    $("#output").val( $("#wmd-input").val().replace(/(&)([A-z]+);/g,replace_named_ent_with_code_ent));
    
    //revert code entity into named
    //$("#output").val( $("#wmd-input").val().replace(/(&amp;#)([0-9]+);/gm,replace_code_ent_with_named_ent));
    //$("#output").val( $("#wmd-input").val().replace(/(&#)([0-9]+);/gm,replace_code_ent_with_named_ent));
    
});