How to preserve anchor tags in links shared using a social media sharing plugin on a one-page website

I ran into an issue today on a one-page scrolling website that is built using fullPage.js and therefore uses anchor links in the page URL to get people to the right place on the website. It is a WordPress website and on the blog, I naturally wanted to incorporate a social media sharing plugin.

The issue I ran into is that when you clicked a link to share the post to, say, Twitter, the link that was getting shared had the hashtag and everything following it – therefore, the anchor link -stripped out. Obviously this was not going to work – I need people to be able to share direct links to the specific post they are referencing, not to the entire website in general.

After some extensive online perusing, I finally found this extremely useful article – https://dev.twitter.com/discussions/512 – which contained exactly what I needed.

According to comment author @benward, “you need to URLEncode” the hashtag in the links, using %23.

Here is the solution that ended up working for me.

I used this line of Javascript to update the links in the social media sharing section of the page:

$(document).ready(function(){
    $('.social-media-links a').each(function(){
        this.href = this.href.replace('#', '%23');
    });
});

Voila! Now when people click the social media share buttons, my anchor links are preserved.