Find/Replace URL's with Javascript

How to change URL's once a page loads

Rob Johnson

By Rob Johnson

Mon Aug 08 2016

#javascript

I recently had a need to ensure all URL's on site A were pointing to site B. What I needed was some javascript that would rewrite the URL's once the page had finished loading, and change any site A links to site B links.

Here's a handy piece of javascript that @n00b2pr0 shared with me that get's the job done.

var linkRewriter = function(a, b) {
  $('a[href*="' + a + '"]').each(function() {
    $(this).attr('href', $(this).attr('href').replace(a, b));
  });
};

linkRewriter('current-domain.com', 'desired-domain.com');
# commerce 14 # seo 5 # tools 6 # amazon 1 # sql 4 # shopify 9 # javascript 13 # projects 4 # css 2 # git 2 # php 3 # analytics 4 # api 6 # monitoring 2 # python 2 # aws 2