samjco samjco - 9 months ago 46
Javascript Question

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-->

Answer Source

Maybe use .endsWith() to check the URL's ending string?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

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