5

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!

Ben Parker
  • 51
  • 3
  • So, I guess what I need to truly figure out is how to use the .replace function of the encodeURIComponent. Then I could just make sure all those special characters aren't touched. I know _**nothing**_ about it is my problem. I looked up the documentation but that seems greek. Sigh, this is why I stick to CSS and HTML. In over my head. – Ben Parker Nov 15 '17 at 15:34

2 Answers2

0

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

jake
  • 488
  • 10
  • 19
  • Interesting. Because when I'm using it here that's not the case. Click the "Tweet It!" Button and you'll see: http://social-media-share.webflow.io/posts/imported-item-11 – Ben Parker Nov 14 '17 at 22:16
  • Look at the page source: `var text = "Coach Pratt has trained thousands of athletes, including professional athletes like Elton Brand & Jewell Loyd, among many others. He's also prepared college players for the NBA Draft for over a decade. Are you ready to take your game to the next level!";` Your text is being escaped before it gets to that point. – jake Nov 14 '17 at 23:04
0

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

Ahmed Musallam
  • 9,523
  • 4
  • 27
  • 47