Last Updated: September 09, 2019
·
541
· rjsamson

Turn an '@' mention into a link to a user profile

This is an example (in Ruby) of how one might check the text of, for example, a user's comment in an app for '@' mentions and replace the plaintext '@' mention with a link to the user's profile (in this example, /users/username).

text.gsub!(/\B\@([\w\-]+)/) do |user|
  if User.find_by_username(u[1 .. -1])
    "<a href=\"/users/#{user[1 .. -1]}\">#{user}</a>"
  else
    u
  end
end