dpberry178 dpberry178 -4 years ago 91
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:

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 + '"';
$('#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 + '"';


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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download