Reputation: 9692
According to what I've read ( this article for instance) you need to escape \
and "
when sending HTML as JSON.
I wanted to use unescape()
, but it is deprecated since JS 1.5.
"Use decodeURI() or decodeURIComponent() instead", w3schools suggests. But decodeURI()
or decodeURIComponent()
do not escape \
and "
.
The response I'm getting looks something like:
"html": {
"searchresult": "<div class=\\\"item\\\">\n\t\t\t<article class=\\\"unit\\\">\n\t\t\t\t<a href=\\\"page2.html\\\">Link<\\/a>\n\n\t\t\t\t\n\t\t\t<\\/article>\n\t\t<\\/div>"
}
I am then saving the following as var markup
:
return $('<textarea/>').html( response ).val();
and am finally left with this semi working html
<div class=\"item\"> <article class=\"unit\"> <a href=\"page2.html\">Link<\/a> <\/article> <\/div>
I now need to remove all \
before "
, and /\
for it work. Guess removing the whitespace in between the tags could be a bonus to.
I have tried the following to remove \"
, which works great.
markup.replace('\\"', '"');
But I can't figure out how to also remove the /\
(plus .replace(blah).replace(blah) doesn't feel right).
This article gave me a hint, but I still feel quite lost in the magic world of Regexp.
Any help much appreciated!
Upvotes: 0
Views: 5793
Reputation: 6032
If you want to change \" to " over and entire string.
markup.toString().replace(/\\"/g,'"');
Upvotes: 2
Reputation: 1075587
You haven't said where your data is coming from, but I'm going to assume at some point you have a valid HTML string (which apparently contains newlines and tabs), and apparently you're trying to make that the searchresult
property of an html
object inside an object, in JSON. Here's how you do that:
var json = JSON.stringify({html: yourString});
Example:
var yourString =
'<div class="item">\n\t\t\t<article class="unit">\n\t\t\t\t<a href="page2.html">Link</a>\n\n\t\t\t\t\n\t\t\t</article>\n\t\t</div>';
var json = JSON.stringify({html: yourString});
snippet.log("The JSON:");
snippet.log(json);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Upvotes: 2