Search code examples
javascriptjqueryhrefsrc

How to set href value from page URL?


If the URL is www.mysite.com/?url=www.google.com?client=xxxxxx

and the a href on the page is

<a href="" id="download" class="button">link</a>

how could I set the href as http://www.google.com by extracting it from ?url=www.google.com to make...

<a href="http://www.google.com" id="download" class="button">link</a>

?

And there is one other factor: if the ?url=www.google.com hasn't got http:// after ?url= then it should be inserted in the href value.


Solution

  • Try this, it's hard to provide a definitive answer as I'm not sure what characters could appear in the the URL you need to parse but this will work with the URL you posted -

    var url = "www.mysite.com/?url=www.google.com?client=xxxxxx"
    url = url.split('?url=')[1].split(/\?|\%3F/)[0];
    if (url.indexOf('http://') == -1)  url = 'http://' + url;
    $("a#download").attr("href",url);
    

    Demo - http://jsfiddle.net/J77J2/