treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] How to replace all "../" href links with "/"

  • I'm having issues with AJAX related links, and need to dynamically find and replace all "../" href's with either a blank "" or a single "/".

    For example: href="../about/" needs to become href="about/", or href="/about/"

    Any thoughts?

  • Found the answer:

    $('a').each(function() {
        $(this).attr("href", function(index, old) {
        return old.replace("../", "");
      });
    });
    
  • Okay, almost solved... The code above only applies to '../' links, however I need it to solve for all variations of this such as '../../' and however many more levels there may be.

    I tried duplicating the script with a different function name for '../../' but the links only change according to whichever script comes first.

    Does anyone know how to extend this simply?

  • You need to do the replace using a regex with the global flag set,

      $('a').each(function(){
        $(this).attr('href', function(index, old) {
          return old.replace(new RegExp('../','g'), '');
        });
      });
    

    Pen is here: http://codepen.io/anon/pen/rBjLe

  • Thanks @Podders, the Pen works perfectly, will test on my project and get back to you. Thanks again!

  • For some reason the above code is removing the last three characters off of any href that includes any kind of symbol...

    For example:

    "../about/" becomes "abo"

    "../contact-form/" becomes "contafo"

    Any clues??

  • Ahh yes it's because the period character in regex represents any character, you can also escape that in the following way,

      $('a').each(function(){
        $(this).attr('href', function(index, old) {
          return old.replace(new RegExp(/\.\.//,'g'), '');
        });
      });
    

    New pen is here http://codepen.io/Podders/pen/lkBAC

    Out of curiosity, why not just make all your links relative links to the root?, or do you not have control over the generated links ?

  • Thanks @Podders, the honest truth is, and I'm embarrassed to admit, that I hadn't properly configured my Mamp development environment correctly for subdomains, so when using root-relative URLs, on a domain such as http://localhost/mysite, the links would always take me back to the localhost root instead of the intended site root.

    I decided to get my hands dirty this morning, and get into setting up virtual hosts on Mamp and I've got everything up and running, so http://localhost/mysite is now http://mysite.localhost, and the root relative URLs are working perfectly.

    I should've done this weeks ago, it would've saved loads of hours, but I have learned a lot along the way.

    Anyways, thanks again for the nudge! (And for your code)