You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过LinkifyJS为不同链接设置个性化rel属性?

问题:为特定链接设置个性化rel属性(如github.com设为follow)

我不清楚如何为个别链接进行个性化格式化,比如给github.com设置rel="follow",当前尝试没生效。能不能在const options里实现类似if(url==mywebsite.com){rel: follow}的判断逻辑?

当前使用的代码:

const beforeEl = document.getElementById('linkify-demo-before')
const afterEl = document.getElementById('linkify-demo-after')

const options = {
  title: "External Link",
  rel: 'nofollow noreferrer noopener',
  target: '_blank',

  formatHref: {
    hashtag: (val) => `https://www.twitter.com/hashtag/${val.substr(1)}`,
    mention: (val) => `https://github.com/${val.substr(1)}`,
  }
}

linkifyHtml("github.com", {
  rel: 'follow',
 });

afterEl.innerHTML = linkifyStr(beforeEl.value, options)
beforeEl.addEventListener('input', () => {
  afterEl.innerHTML = linkifyStr(beforeEl.value, options)
  
})
解决方案

linkify.js的rel选项支持函数形式,可以根据链接的href值动态返回对应的rel属性,完全满足你的需求。

修改options中的rel配置,将固定字符串替换为判断函数即可:

const options = {
  title: "External Link",
  // 动态判断rel属性
  rel: (href) => {
    // 匹配github.com相关链接
    if (href.includes('github.com')) {
      return 'follow';
    }
    // 其他链接使用默认规则
    return 'nofollow noreferrer noopener';
  },
  target: '_blank',

  formatHref: {
    hashtag: (val) => `https://www.twitter.com/hashtag/${val.substr(1)}`,
    mention: (val) => `https://github.com/${val.substr(1)}`,
  }
}

说明

  1. 函数接收当前链接的href作为参数,可根据实际需求编写判断逻辑(比如匹配特定域名、路径等)
  2. 你之前单独调用的linkifyHtml("github.com", {rel: 'follow'})并未作用到输入框的处理逻辑中,实际生效的是linkifyStr调用时传入的全局options,所以将判断逻辑写入全局options即可覆盖所有链接的rel规则

内容的提问来源于stack exchange,提问作者Maksior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:50:54