使用 Javascript 获取和替换字符串

Get and replace string using Javascript

提问人:Stellan Coder 提问时间:9/1/2022 最后编辑:Stellan Coder 更新时间:9/2/2022 访问量:60

问:

我的网站有很多链接,我正在尝试将所有目标替换为 .我怎样才能用javascript做到这一点?a href_top_blank

它将在我的网页中找到所有内容并替换为_top_blank

我是这样尝试的:

// const string = document.getElementsByTagName('a')[0].innerHTML
const string = document.querySelector("_top"); //getting string
var newstring = string.replace(/_top/, '_blank'); //trying to replace string in whole page
const myTimeout = setTimeout(selecteAd, 2000); //set timeout so webpage get loaded full
<!-- example string -->
<a data-asoch-targets="imageClk" href="https://www.eample.com" target="_top" x-ns-8l6in-e="2"><canvas class="ns-8l6in-e-3 image" x-ns-8l6in-e="3" width="600" height="314"></canvas></a>

更新:

数据来自 Google adsense 代码。(在 Stackoverflow 的其他部分也有类似的解决方案,但我仍然无法成功替换如何使用 javascript 获取 DIV 子元素async )

JavaScript HTML jQuery ajax DOM

评论


答:

0赞 ControlAltDel 9/1/2022 #1

使用 querySelectorAll

$(function() {
  document.querySelectorAll("a[target=_top]").forEach(function(elem) {
    this.target="_blank";
  });
  });
});
0赞 Stellan Coder 9/2/2022 #2

归功于删除答案的原始答案:

document.querySelectorAll('a[target="_top"]').forEach(el => el.target = '_blank');
<a href="https://www.example.com" target="_top">foo</a><br />
<a href="https://www.example.com" target="_top">bar</a>