Search code examples
javascriptjqueryurlsocial-networking

Need a quick jquery solution to capture the current url and inject it into another url link


My brain is fried ATM and I have a looming deadline, I am looking for a way to grab the currently viewed pages url and place it into another link for bookmarking/social links.

Facebook link:http://www.facebook.com/share.php?u=[PAGEURL]
Myspace link:http://www.myspace.com/Modules/PostTo/Pages/?u=[PAGEURL]
Twitter link: http://twitter.com/home?status=Check+this+out:+[PAGEURL]
Stumble Upon link:http://www.stumbleupon.com/submit?url=[PAGEURL]
Digg link: http://digg.com/submit?phase=2&url=[PAGEURL]

I need to replace [PAGEURL] with the URL for the page being viewed. Any help is most appreciate. i have been looking for a while now and can't seems to find an answer that fits this specific circumstance.


Solution

  • It'd help to see what kind of structure those links are in. But, here's some jQuery that might point you in a good direction. It assumes your social bookmarking links are in a container with id="socials", but you can mash the selector to do whatever it takes to get hold of your social links.

    $(function() {
        var links = $('#socials a'),
            matchExp = /\[PAGEURL\]/,
            currentURL = location.href;
    
        links.each(function() {
            var currentHREF = $(this).attr('href');
            if (currentHREF.match(matchExp)) {
                $(this).attr('href',currentHREF.replace(matchExp,currentURL));
            }
        });
    
    });
    

    This uses the attr function to get where the link points to, then a regular expression (eww!) to check if the link has [PAGEURL] in it, and to replace [PAGEURL] with location.href, which is the url of the current page. Here's a handy regexp tester.