2

im working on a piece of code where im getting the html from another server through php with file_get_contents.

Then some of the links needs to get the original domain onto it so that they link to the proper places, for most of my links ive just been able to replace the whole line as they were static but with this one being dynamic i need to replace just a part of it.

Ive done it this way:

<script>$(document).ready(function(){
  $(".view").each(function(){
        this.href = this.href.replace("/tourney/", "http://binarybeast.com/tourney/");
    })
});</script>

I however am getting the problem that when doing this im getting double domains even though no domain was made in the first link like this:

<a class="view" href="http://localhosthttp://binarybeast.com/tourney/load_match/169049">View Details</a>

Original line:

<a class="view" href="/tourney/load_match/169049">View Details</a>
Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
Martin Hobert
  • 203
  • 1
  • 3
  • 10
  • I ran into a [similar problem](http://stackoverflow.com/questions/9222026/method-for-selecting-elements-in-sizzle-using-fully-qualified-urls) relating to the difference between `this.href` and `$(this).attr('href')`. – Jared Farrish Mar 26 '13 at 01:45

4 Answers4

0

Use attr("href") to access the attribute:

this.href = $(this).attr("href").replace(...)

Or without jQuery the getAttribute function.

The href property will always return the absolute path. Here's an example:

$("<a href='test'>")[0].href
//"http://stackoverflow.com/questions/15627830/href-replace-giving-me-double-domain-http-localhosthttp-mydomain-com/test"
$("<a href='test'>").attr("href")
//"test"
Matt Zeunert
  • 16,075
  • 6
  • 52
  • 78
0

Try this:

this.setAttribute("href",this.getAttribute("href").replace("/tourney/","http://.../"));

This accesses the attribute as you write it, not the property as parsed by the browser.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Here's a slightly different way of looking at it:

$(document).ready(function(){
    $(".view").each(function(){
        var parts = this.href.split('/').slice(3);

        if (parts[0] == 'tourney') {
            this.href = '/' + parts.join('/');
        }
    });
});

http://jsfiddle.net/userdude/aAXYM/

This works because the urls in this.href will always be expanded, thus you can remove the first part (the domain is in parts[2]), test, and reassemble. If you want to add http://yoursite.com, just add that to the first part, as 'http://yoursite.com/' + or use:

window.location.protocol + '//' + window.location.hostname + '/' + ... 

if it's appropriate.

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
0

The href property returns the full, absolute url. Either change the replace-regex to /.*?\/tourney\//, or assign to the host property:

this.host = "binarybeast.com";
Bergi
  • 630,263
  • 148
  • 957
  • 1,375