Convert special characters to HTML in Javascript



  • 3 Answer(s)

    Try this method with managing single or double quotes:

    return mystring.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
    
    
    Answered on December 28, 2018.
    Add Comment

    Using browser’s inbuilt HTML escape functionality.

    • Create a element in the DOM tree and set the innerText of the element to the string.
    • Extract the innerHTML of the element. So that the browser will return an HTML encoded string.
    function HtmlEncode(s)
    {
      var el = document.createElement("div");
      el.innerText = el.textContent = s;
      s = el.innerHTML;
      return s;
    }
    

    Run the code:

    alert(HtmlEncode('&;\'><"'));
    

    Result is:

    &amp;;'&gt;&lt;"
    
    Answered on December 28, 2018.
    Add Comment

    Encoding non alphabetic character to its html code is given in below code:

    function HTMLEncode(str) {
        var i = str.length,
            aRet = [];
     
        while (i--) {
            var iC = str[i].charCodeAt();
            if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
                aRet[i] = '&#'+iC+';';
            } else {
                aRet[i] = str[i];
            }
        }
        return aRet.join('');
    }
    
    Answered on December 28, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.