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

How to add rel="nofollow" to all external links that do not related to my domain with javascript?

我有以下包含三个 link 的 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。从上面的代码可以看出,有两个内部 link 和一个外部

我需要编写 "magic" 函数,将 rel="nofollow" 属性添加到所有外部 link(不是内部的)。所以我需要得到以下结果:

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'), '" rel="nofollow">');
}

很遗憾,我的正则表达式似乎不起作用。执行后 addNoFollowsToExternal(html) rel="nofollow" 不要添加到外部 link 与 href="https://google.com"

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

您的正则表达式中存在一些小错误。这是更正后的版本:

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

    return html.replace(new RegExp(str, 'igm'), '" 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);
    }