search

Home  >  Q&A  >  body text

Using Javascript to get and replace strings

My website has a lot of links and I'm trying to replace all the a href targets _top with _blank. How can I implement this functionality using JavaScript?

It will find all the _top in my page and replace them with _blank

I tried the following:

// const string = document.getElementsByTagName('a')[0].innerHTML
const string = document.querySelector("_top"); //获取字符串
var newstring = string.replace(/_top/, '_blank'); //尝试在整个页面中替换字符串
const myTimeout = setTimeout(selecteAd, 2000); //设置延时以确保网页完全加载
<!-- 示例字符串 -->
<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>

renew:

Data comes from Google AdSense's async code. (Found similar solutions in other parts of Stackoverflow, but I still can't replace. How to get DIV child elements using JavaScript)

P粉364129744P粉364129744452 days ago564

reply all(1)I'll reply

  • P粉517814372

    P粉5178143722023-09-08 10:06:28

    Use querySelectorAll

    $(function() {
      document.querySelectorAll("a[target=_top]").forEach(function(elem) {
        this.target="_blank";
      });
      });
    });

    reply
    0
  • Cancelreply