tags:

views:

7877

answers:

8

Does any one know how to convert special characters to HTML in Javascript?

Example:

'&' (ampersand) becomes '&amp'
'"' (double quote) becomes '&quot' when ENT_NOQUOTES is not set.
''' (single quote) becomes '&#039' only when ENT_QUOTES is set.
'<' (less than) becomes '&lt'
'>' (greater than) becomes '&gt'

+2  A: 

You need a function that does something like

return mystring.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");

But taking into account your desire for different handling of single/double quotes.

Steven
A: 
function convert(str)
{
  str = str.replace(/&/g, "&amp;");
  str = str.replace(/>/g, "&gt;");
  str = str.replace(/</g, "&lt;");
  str = str.replace(/"/g, "&quot;");
  str = str.replace(/'/g, "&#039;");
  return str;
}
Matt Hanson
A: 
<html>
<body>
<script type="text/javascript">
var str= "&\"'<>";
alert('B4 Change:\n' + str);
str= str.replace(/\&/g,'&amp;');
str= str.replace(/</g,'&lt;');
str= str.replace(/>/g,'&gt;');
str= str.replace(/\"/g,'&quot;');
str= str.replace(/\'/g,'&#039;');
alert('After change:\n' + str);
</script>
</body>
</html>

use this to test: http://www.w3schools.com/js/tryit.asp?filename=tryjs_text

+22  A: 

Even though the answer to this question has already been accepted, I think I should still post my answer in the interest of the OP:

The best way in my opinion is to use the browser's inbuilt HTML escape functionality to handle many of the cases. To do this simply create a element in the DOM tree and set the innerText of the element to your string. Then retrieve the innerHTML of the element. The browser will return an HTML encoded string.

function HtmlEncode(s)
{
  var el = document.createElement("div");
  el.innerText = el.textContent = s;
  s = el.innerHTML;
  delete el;
  return s;
}

Test run:

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

Output:

&amp;;'&gt;&lt;"

This method of escaping HTML is also used by the Prototype JS library though differently from the simplistic sample I have given.

Note: You will still need to escape quotes (double and single) yourself. You can use any of the methods outlined by others here.

Cerebrus
+4  A: 

this generic function encodes every non alphabetic character to its htmlcode (numeric):

    function HTMLEncode(str){
     var aStr = str.split(''),
         i = aStr.length,
         aRet = [];

     while (--i) {
      var iC = aStr[i].charCodeAt();
       if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
        aRet.push('&#'+iC+';');
       } else {
        aRet.push(aStr[i]);
       }
    }
    return aRet.reverse().join('');
   }
KooiInc
This is just what I was looking for! This will be much faster than trying to manually replace any special characters...
Steve Harrison
A: 
function escape (text)
{
  return text.replace(/[<>\&\"\']/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; });
}

alert(escape("<>&'\""));
Chris
+1  A: 
KygG
A: 

Yes, but if you need to insert the resulting string somewhere without it being converted back, you need to do:

str.replace(/'/g,"&amp;#39;"); // and so on

graham