Twitter Share encodeURIcomponent Struggle

Viewed 1268

I'm working on a project and I'm having some trouble with the encodeURIcomponent function. The site is a social media content bank that allows me to store copy in a CMS and display it on it's on page with links and buttons to share to social media sites. I'm struggling with the Twitter component and need some help. Here's my code:

   
   
function tweetClick() {
 var url = "http://urlfromcms.com";
 var text = "I'm getting this text dynamically from the CMS too.";
 window.open('http://twitter.com/share?url='+encodeURIComponent(url)+'&text='+encodeURIComponent(text), '');
   }                   
<a class="shareitbutton w-button" href="#" target="_blank" title="Tweet" onclick="tweetClick(); return false;">Tweet It!</a>

This is working like a champ with one problem. If the copy has an ampersand, apostrophe, quotes, etc. then it get's encoded as well and and the tweet needs to be edited which defeats the purpose. How to I encode to get the %20 in the spaces that twitter needs but leave my ampersands and apostrophes alone?

Any help would be greatly appreciated!

2 Answers

Your code seems to work as-is. Twitter is smart enough to decode the text you give it:

enter image description here

enter image description here

The issue is that the text you get from the CMS has encoded html entities

you can decode the HTML entities in text by using this answer

and then put the decoded string in the window.open call

Related