【问题标题】:Change all of a specific term in href to another specific term with javascript使用 javascript 将 href 中的所有特定术语更改为另一个特定术语
【发布时间】:2017-02-28 10:13:51
【问题描述】:

我希望更改网页上许多链接的一部分。我想将任何具有“oldTag”的链接更改为“newTag”。

例如。 www.google.com/WillBeDifferent/oldTag 到 www.google.com/WillBeDifferent/newTag

基本上任何出现 oldTag 的链接我都想用 newTag 替换它。我对此并不陌生,但我已经研究了几天,但我想出的任何东西似乎都不起作用。

上下文是我让 Google 跟踪代码管理器检查是否存在 cookie,如果存在,它将触发一个标签来更改所有指向 newTag 的链接。

不确定我是否应该或可以使用 jQuery 或 Regex...

这是我在网上搜索的结果。

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

它用 oldTerm 替换了所有链接,但用 http://www.google.com/newTerm 替换了它们。

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

无法使其正常工作,但在此处的其他地方找到了它。

现在不知道该去哪里找...任何帮助都会很棒。

【问题讨论】:

    标签: javascript jquery html regex href


    【解决方案1】:

    你很亲密,但需要使用 * 而不是 ^

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

    【讨论】:

    • 谢谢,成功了。我唯一需要做的另一件事是将 $ 更改为 jQuery,因为我得到 $ is not a function 错误。也许这与我从谷歌标签管理器加载脚本的事实有关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    相关资源
    最近更新 更多