What is the HtmlSpecialChars equivalent in JavaScript?
There is a problem with your solution code--it will only escape the first occurrence of each special character. For example:
escapeHtml('Kip\'s <b>evil</b> "test" code\'s here');
Actual: Kip's <b>evil</b> "test" code's here
Expected: Kip's <b>evil</b> "test" code's here
Here is code that works properly:
function escapeHtml(text) {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
Update
The following code will produce identical results to the above, but it performs better, particularly on large blocks of text (thanks jbo5112).
function escapeHtml(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
That's HTML Encoding. There's no native javascript function to do that, but you can google and get some nicely done up ones.
E.g. http://sanzon.wordpress.com/2008/05/01/neat-little-html-encoding-trick-in-javascript/
EDIT:
This is what I've tested:
var div = document.createElement('div');
var text = document.createTextNode('<htmltag/>');
div.appendChild(text);
console.log(div.innerHTML);
Output: <htmltag/>
Worth a read: http://bigdingus.com/2007/12/29/html-escaping-in-javascript/
escapeHTML: (function() {
var MAP = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
var repl = function(c) { return MAP[c]; };
return function(s) {
return s.replace(/[&<>'"]/g, repl);
};
})()
Note: Only run this once. And don't run it on already encoded strings e.g. &
becomes &amp;
Here's a function to escape HTML:
function escapeHtml(str)
{
var map =
{
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return str.replace(/[&<>"']/g, function(m) {return map[m];});
}
And to decode:
function decodeHtml(str)
{
var map =
{
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
};
return str.replace(/&|<|>|"|'/g, function(m) {return map[m];});
}
With jQuery it can be like this:
var escapedValue = $('<div/>').text(value).html();
From related question Escaping HTML strings with jQuery
As mentioned in comment double quotes and single quotes are left as-is for this implementation. That means this solution should not be used if you need to make element attribute as a raw html string.