formatting individual link with linkifyjs

181 Views Asked by At

I cant understand how I can format few links in individual way... for example github.com with rel:follow (not working). How I can building something like a IF: if(url==mywebiste.com){rel: follow} in const options?? is it possible? https://linkify.js.org/docs/options.html#format

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)
  
})
1

There are 1 best solutions below

0
nfrasser On

Most options in linkifyjs, including rel, accept a function. For each link encountered, this function is called with the href as the first argument and the type of link as the second argument.

Example options with the behaviour you're looking for:

const options = {
  rel: (href, type) => {
    if (type === 'url' && href.startsWith('https://mywebsite.com') {
        return null;
    } else {
        return 'nofollow noreferrer noopener'
    }
  }
}

const linkified = linkifyStr("... https://mywebsite.com/about ...", options)
console.log(linkified)