使用 javascript 将 href 中的所有特定术语更改为另一个特定术语
Change all of a specific term in href to another specific term with javascript
我想更改网页上许多 link 的一部分。我想将任何具有 "oldTag" 的 link 更改为 "newTag"。
例如。
www.google.com/WillBeDifferent/oldTag
到
www.google.com/WillBeDifferent/newTag
基本上任何 link 出现 oldTag 的地方我都想用 newTag 替换它。我对此很陌生,但我已经研究了几天,但我想不出的任何东西似乎都行不通。
上下文是我让 Google 标签管理器检查是否存在 cookie,如果存在,它将触发标签以将所有 link 更改为新标签。
不确定我是否应该或可以使用 jQuery 或 Regex...
这是我在网上搜索的结果。
var anchors = document.querySelectorAll('a[href*="oldTerm"]');
Array.prototype.forEach.call(anchors, function (element, index) {
element.href ="newTerm"; });
它用 oldTerm 替换了所有 link,但用 http://www.google.com/newTerm 替换了它们。
$("a[href^='oldTerm']")
.each(function() {
this.href = this.href.replace(/oldTerm/g,
"newTerm");
});
无法使其正常工作,但在此处的其他地方找到了它。
不知道现在去哪里看...任何帮助都会很棒。
你很接近但需要使用 * 而不是 ^
$("a[href*='oldTerm']")
.each(function() {
this.href = this.href.replace(/oldTerm/g, "newTerm");
});
我想更改网页上许多 link 的一部分。我想将任何具有 "oldTag" 的 link 更改为 "newTag"。
例如。 www.google.com/WillBeDifferent/oldTag 到 www.google.com/WillBeDifferent/newTag
基本上任何 link 出现 oldTag 的地方我都想用 newTag 替换它。我对此很陌生,但我已经研究了几天,但我想不出的任何东西似乎都行不通。
上下文是我让 Google 标签管理器检查是否存在 cookie,如果存在,它将触发标签以将所有 link 更改为新标签。
不确定我是否应该或可以使用 jQuery 或 Regex...
这是我在网上搜索的结果。
var anchors = document.querySelectorAll('a[href*="oldTerm"]');
Array.prototype.forEach.call(anchors, function (element, index) {
element.href ="newTerm"; });
它用 oldTerm 替换了所有 link,但用 http://www.google.com/newTerm 替换了它们。
$("a[href^='oldTerm']")
.each(function() {
this.href = this.href.replace(/oldTerm/g,
"newTerm");
});
无法使其正常工作,但在此处的其他地方找到了它。
不知道现在去哪里看...任何帮助都会很棒。
你很接近但需要使用 * 而不是 ^
$("a[href*='oldTerm']")
.each(function() {
this.href = this.href.replace(/oldTerm/g, "newTerm");
});