Convert special characters to HTML in Javascript
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;
return s;
}
Test run:
alert(HtmlEncode('&;\'><"'));
Output:
&;'><"
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.
You need a function that does something like
return mystring.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
But taking into account your desire for different handling of single/double quotes.