Search code examples
javascriptjqueryhtmlregexhref

Change all of a specific term in href to another specific term with javascript


I am looking to change part of many links on a webpage. I want to change any link that has "oldTag" to "newTag".

Ex. www.google.com/WillBeDifferent/oldTag to www.google.com/WillBeDifferent/newTag

Basically any link where oldTag shows up I want to replace it with newTag. I am new to this but I have been researching for a few days and nothing I can come up with seems to work.

The context is I have Google Tag Manager checking to see if a cookie is present and if it is then it will trigger a tag to change all of the links to the newTag.

Not sure if I should or can use jQuery or Regex...

Here is what I have played with from scouring the internet.

var anchors = document.querySelectorAll('a[href*="oldTerm"]');
    Array.prototype.forEach.call(anchors, function (element, index) { 
    element.href ="newTerm"; });

It replaced all of the links with the oldTerm but replaced them with http://www.google.com/newTerm.

$("a[href^='oldTerm']")
.each(function() {
this.href = this.href.replace(/oldTerm/g, 
     "newTerm");
});

Could not get this to work but found it somewhere else on here.

Not sure where to look now... any help would be great.


Solution

  • you are very close but need to use * instead of ^

    $("a[href*='oldTerm']")
      .each(function() {
        this.href = this.href.replace(/oldTerm/g, "newTerm");
      });