繁体   English   中英

如何使用javascript将rel =“ nofollow”添加到与我的域不相关的所有外部链接?

[英]How to add rel=“nofollow” to all external links that do not related to my domain with javascript?

我有以下带有三个链接的html字符串:

var html = '
   <a href="http://www.example.com/help">Go to help page</a>
   <a href="http://blog.example.com">Go to blog page</a>
   <a href="https://google.com">Go google</a>
';

我的域名是example.com 从上面的代码可以看到,有两个内部链接和一个外部链接。

我需要编写将rel="nofollow"属性添加到所有外部链接(而非内部链接)的“魔术”函数。 所以我需要得到以下结果:

var html = '
   <a href="http://www.example.com/help">Go to help page</a>
   <a href="http://blog.example.com">Go to blog page</a>
   <a href="https://google.com" rel="nofollow">Go google</a>
';

我正在尝试编写该函数,而这是我当时拥有的:

function addNoFollowsToExternal(html) {
  // List of allowed domains
  var whiteList = ['example.com', 'blog.example.com'];

  // Regular expression
  var str = '(<a\s*(?!.*\brel=)[^>]*)(href="/https?://)((?!(?:(?:www\.)?' + whiteList.join(',') + '))[^"]+)"((?!.*\brel=)[^>]*)(?:[^>]*)>',

  // execute regexp and return result
  return html.replace(new RegExp(str, 'igm'), '$1$2$3"$4 rel="nofollow">');
}

不幸的是我的正则表达式似乎不起作用。 执行addNoFollowsToExternal(html) rel="nofollow"请勿添加到带有href="https://google.com"外部链接

请帮助我修正正则表达式以解决任务。

您的RegEx有一些小错误。 这是更正的版本:

function addNoFollowsToExternal(html){
    var whiteList = ['([^/]+\.)?example.com'];
    var str = '(<a\s*(?!.*\brel=)[^>]*)(href="https?://)((?!(?:' + whiteList.join('|') + '))[^"]+)"((?!.*\brel=)[^>]*)(?:[^>]*)>';

    return html.replace(new RegExp(str, 'igm'), '$1$2$3"$4 rel="nofollow">');
}

您还可以使用下面的功能

private function _txt2link($text){

         $regex = '/'
          . '(?<!\S)'
          . '(((ftp|https?)?:?)\/\/|www\.)'
          . '(\S+?)'
          . '(?=$|\s|[,]|\.\W|\.$)'
          . '/m';

        return preg_replace_callback($regex, function($match)
        {
            return '<a'
              . ' target="_blank"'
              . ' rel="nofollow"'
              . ' href="' . $match[0] . '">'
              . $match[0]
              . '</a><br/>';
        }, $text);
    }

暂无
暂无

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

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