Make addition to href URL string

I have the need to make changes to all hyperlinks on a page using Java Script. Currently the the tags are laid out in this maner

<a href="/Level1/Level2/Level3/bla bla bla.aspx"

The change I am really struggling with (Being a absolute Noob in this field) is how i can make the following change and add in another level? Its subsite with the same structure;

<a href="/Level1/Level2/Level3/+Level4/bla bla bla.aspx" 

Sections of the URL pre and post the addition of "level 4" will remain the same. I need this change to be applied to all Hyperlinks on the page that do not have the level 4 portion already present.

Apologies for the shocking request. First time posting.

3 answers

  • answered 2019-04-15 06:16 gavgrif

    Get all the hrefs - if the href does not have the required level 4 then add the level with a simple .replace() with the addded level - then apply as the href attribute.

    Note that links 1 and 3 do not have the level 4 so will be affected by the if condition, wherease the link 2 already has it so it will not be affected.

    let links = document.querySelectorAll('a');
    links.forEach(function(link) {
     let originalHref = link.getAttribute('href');
     if(originalHref.indexOf('+Level4') == -1) {
       link.setAttribute('href', originalHref.replace('Level3/','Level3/+Level4/'));
    a {
     display: block;
     margin-bottom: 8px;
    <a href="/Level1/Level2/Level3/option1.aspx">Option 1</a>
    <a href="/Level1/Level2/Level3/+Level4/option2.aspx">Option 2</a>
    <a href="/Level1/Level2/Level3/option3.aspx">Option 3</a>

  • answered 2019-04-15 06:28 Kamil Kie┼éczewski


     a.href= a.href.replace(/(\/Level1\/Level2\/Level3)(?!\/Laravel4)/,"$1/+Laravel4"));

    regexp explanation

    • (\/Level1\/Level2\/Level3) find links with prefix (group $1)
    • (?!\/Laravel4) but not containing Laravel4
    • "$1/+Laravel4" replace matched string(group $1) with group $1 with suffix

     a.href= a.href.replace(/(\/Level1\/Level2\/Level3)(?!\/Laravel4)/,"$1/+Laravel4"));
    // INFO
    <a href="/Level1/Level2/Level3/bla bla bla.aspx">link 1</a>
    <a href="/Level1/Level2/Level3/Laravel4/terefere.aspx">link 2</a>
    <a href="/Level1/Level2/Level3/zzzz.aspx">link 3</a>

  • answered 2019-04-15 07:14 BMErEr

    location.href is gave you tu url so:

    var currentUrl= location.href;
    currentUrl = currentUrl.replace("level1","level1/level2")
    location.href = currentUrl;

    I don't understand you clearly but this need to be solve your problem.