According to what I've read (the below links for instance) you need to escape \
and "
when sending HTML as JSON, but that's all you need to escape.
- http://www.thorntech.com/2012/07/4-things-you-must-do-when-putting-html-in-json/
- In jQuery, I am returning HTML in a JSON result, what do I have to escape?
- Escaping HTML strings with jQuery
I have two ways of getting my data:
1) From Front-end
I am fetiching the html from the page like so:
$('#myDiv').html()
Which gives me a string containing html, newlines and white spaces.
<a class="some-class" href="somepage.html">
<figure class="someClass">
<img src="/img/pic.png" alt="">
</figure>
</a>
I can now choose to either use JSON.stringify
(which apparently is unnecessary as I only have to escape \ and ") to get:
"<a class=\"some-class\" href=\"somepage.html\">\n <figure class=\"someClass\"> \n <img src=\"/img/pic.png\" alt=\"\">\n </figure>\n </a>"
and then JSON.parse
later to turn it back into HTML and insert into the DOM.
Or I can use escapeHTML()
instead of JSON.Stringify:
escapeHTML: function(htmlString) {
var chr = {
'"': '"',
'&': '&',
"'": ''',
'/': '/',
'<': '<',
'>': '>'
};
return html.htmlString(/[\"&'\/<>]/g, function (a) { return chr[a]; });
}
which gives me:
<a class="some-class" href="somepage.html">
<figure class="someClass">
<img src="/img/pic.png" alt="">
</figure>
</a>
I can then unescape it by using the following Solution A:
return $('<textarea/>').html( response ).val();
2) From backend:
The above works great, but if the response I'm getting (from the backend service) looks like the following (escaped " and /), it doesn't work.
<a class=\"some-class\" href=\"somepage.html\">\n<figure class=\"someClass\">\n<img src=\"/img/pic.png\" alt=\"\">\n<\/figure>\n<\/a>
I first use Solution A.
Then to to get rid of \"
I use:
markup.replace('\\"', '"');
Clearly that doesn't remove \/
.
My question is therefor: how can I combine a regexp to unescape both \
and "
if I am to use the escapeHTML()
way?
Would it be better to use escapeHTML()
or JSON.Stringify
when passing HTML as JSON?