简体   繁体   English

如果链接有 http 或 https,则将目标空白添加到链接

[英]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:我试图在文本中找到所有具有 http 或 https 的链接,并向它们添加目标空白,它们存在于以下代码中:

    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.但是,它不起作用,具有 http 或 https 的链接没有目标空白。 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');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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