jquery change all urls of a site

**I know I can use Jquery or javascript to change urls sitewide. with:

$.each($('a'), function(i,v){
    var oldULR =  $(v).attr('href');
    var newURL = oldULR.replace('/fold/fold', '/newfolder');
    $(this).attr('href', newURL);

});

However I am only trying to change the url if it DOES NOT have add or delete on the end of the url. I have the following url examples:**

<a href="http://example.com/fold/fold/AAA">AAA</a>
<a href="http://example.com/fold/fold/AAA/add">Add new AAA</a>
<a href="http://example.com/fold/fold/BBB/delete">Delete BBB</a>
<a href="http://example.com/fold/fold/CCC/add">Add new CCC</a>

**So I only want to change /fold/fold to /newfolder if there isn't an ending of add or delete..

So the final urls would look like**:

<a href="http://example.com/newfolder/AAA">AAA</a>  <!--changed-->
<a href="http://example.com/fold/fold/AAA/add">Add new AAA</a> <!--no change-->
<a href="http://example.com/fold/fold/BBB/delete">Delete BBB</a> <!--no change-->
<a href="http://example.com/fold/fold/CCC/add">Add new CCC</a> <!--no change-->

Answers 1

  • Use a conditional statement can do this

    $.each($('a'), function(i,v){
        var oldURL =  $(v).attr('href');
        if (!oldURL.endsWith('/add') && !oldURL.endsWith('/delete')) {
            var newURL = oldULR.replace('/fold/fold', '/newfolder');
            $(this).attr('href', newURL);        
        }
    });
    

Related Articles