简体   繁体   中英

Add target blank to links if it has http or https

I am trying to find in a text all links that have http or https and add target blank to them it they exist with this code:

    const text   = this.node.body;
    const regex = /https?:\/\//i;
    let newStr = text.replace(regex, '$& target="_blank"');

    return newStr;

But, it doesn't work, the links that have http or https are not getting target blank. What is the correct way of doing this? This is the example text:

<p><a href='www.link.com'>Link</a></p><p><div><img src='http://image.jpg' /></div></p><p><a href='http://link.html'>link</a></p>

And this is the result of the code:

<p><a href='www.link.com'>Link</a></p><p><div><img src='http:// target="_blank"/image.jpg' /></div></p><p><a href='http://link.html'>link</a></p>

Try this out:

document.querySelectorAll('a[href^="http"]').forEach(function(e) {
  e.setAttribute('target', '_blank');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM