Question

I have a text paragraph where it may have external or internal URL. User will enter this text. So, I want external links should add rel=nofollow and internl links won't be having rel=nofollow attribute.

Internal links can be:

 <a href=http://www.mysite.com"> My Site </a> 

or
<a href="/articles/1-world-cup-cricket-2015"> World cup schedule </a>

External link is as usual anything...

My current function is adding rel=nofollow to all internal and external links.

def add_nofollow html
  html.gsub(/\<a href=["'](.*?)["']\>(.*?)\<\/a\>/mi, '<a href="\1" rel="nofollow" target="_new" >\2</a>')
end

The question is how do I add the rel=nofollow to external links only?

Was it helpful?

Solution 2

In Ruby on Rails you can use regex to find urls and add rel=nofollow to them.

def add_nofollow html

 html.scan(/(\<a href=["'].*?["']\>.*?\<\/a\>)/).flatten.each do |link|
   if link.match(/\<a href=["'](http:\/\/|www){0,1}((localhost:3000|mysite.com)(\/.*?){0,1}|\/.*?)["']\>(.*?)\<\/a\>/)
    else
    link.match(/(\<a href=["'](.*?)["']\>(.*?)\<\/a\>)/)
    html.gsub!(link, "<a href='#{$2}' rel='nofollow' target='_new' >#{$3}</a>" )
    end
  end
  html
end

`

Cheers!

OTHER TIPS

see this link for my example. is use regex <a href=["']((http://www.mysite.com)(/.*?){0,1}|/.*?)["']\>(.*?)\<\/a\> to get all link match your internal link.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top