tags:

views:

49

answers:

4

I need to select all local links, regardless of if the start with

  • /path/to/page
  • http://mydomain.com/path/to/page
  • https://mydomain.com/path/to/page

and replace them with

  • /#/path/to/page

Thanks for your help.

Edit: As pointed out by dvhh in a comment, a better solution would be to target clicks. So sorry, I won't be testing solutions to mark a correct answer. Thanks for your help

Edit 2: Posted a new question about doing this via a click.

+1  A: 

This should select all the anchor tags.

$("a[href*='https://mydomain.com/path/to/page'] a[href*='/path/to/page']  a[href*='http://mydomain.com/path/to/page']")

This should replace all the hrefs

$("a[href*='https://mydomain.com/path/to/page'] a[href*='/path/to/page']  a[href*='http://mydomain.com/path/to/page']").each(function () {
  var $this = $(this);
  var currentHref = $this.attr('href');
  $this.attr("href","#/" + currentHref.substring(currentHref.indexOF("/path/to/page"), currentHref.length - 1));

})
John Hartsock
A: 

You should be able to do something like this:

$('a').each(function() {
    if ( this.host === 'mydomain.com' || this.getAttribute('href').indexOf('/') === 0) {
        this.href = "/#" + this.pathname;
    }
});

It checks to see if the href.host matches the domain.com or if the first character of href is /, and if so it sets the href to /# plus the current pathname part of the href.

I'm using the native getAttribute() because I think it is safest in terms of getting the actual original attribute that was set. Perhaps it wouldn't make a difference.

patrick dw
+1  A: 

what you requested for

$("a").each(
    function(index,element) {
        if(element.href.indexOf("https://mydomain.com/")==0) {
            $("a").attr("href",element.href.replace("https://mydomain.com/","/#/"));
        }
    }
}
dvhh
A: 

pretty simple one

$(function () {
    $('a').each(function () {
        $(this).attr('href', '/#' + pathname);
    });
});
Ninja Dude