dpberry178 dpberry178 - 3 months ago 7
Javascript Question

What is the correct way to construct a URL from the content of a JSON element to avoid encoded characters in output?

I am trying to send the output of a JSON message to Twitter like so:



$.getJSON(
'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=',
'json',
function(data) {
$("#quote-content").html(data[0].content + "<br> --" + data[0].title);
tweetText = data[0].content.replace(/<\/?[^>]+>/gi, '');
url = "https://twitter.com/intent/tweet?text=" + '"' + tweetText + '"';
console.log(url);
$('#tweet').attr("href", url);
}
);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





The issue is, when there is a character present in the data such as a single quote (apostrophe), dash, or double quote, the content cuts off like this:

Original String:


Almost everything – all external expectations, all pride, all fear of
embarrassment or failure – these things just fall away in the face of
death, leaving only what is truly important.


Tweet cuts off at first unhandled character:


"Almost everything


Screenshot Here

========================================================================

In order to correct that issue, I tried changing:

url = "https://twitter.com/intent/tweet?text=" + '"' + tweetText + '"';


to

url = "https://twitter.com/intent/tweet?text=" + '"' + encodeURIComponent(tweetText) + '"';


Now the output is like this:

Original String:


Best thing about creating something is that it starts living it’s own
life.


Tweet text is now fully displaying, but showing encoded characters:

Screenshot here

Sorry, I had to post a screenshot because Stack Overflow was actually escaping the characters correctly!

My question is, how do I get the original text (with all characters) to display when sending the quote to Twitter?

Thanks for your help!

Answer

I got around it with this:

var elem = document.createElement('textarea');
            elem.innerHTML = tweetText;
            tweetText = elem.value;

Basically, the text was sent as HTML encoded from the API so I had to decode it prior to building the URL.