I’m making a mentions feature right now so when a user types in @, the next part they type for a username is clickable until a space appears. This is assuming they type in a username correctly, which only have letters and numbers. I need it to work though so if they type “Hi @jon!” that it finds the exclamation point (or any symbol that is not a letter or number) as not part of the username and excludes it instead of just looking for the following space.
This is what I have:
while @comment.content.include? "@" do
at = @comment.content.index('@')
space = @comment.content.index(' ', at)
length = space - at
usernotag = @comment.content[at + 1,length - 1]
userwtag = @comment.content[at,length]
@user = User.where(:username => usernotag.downcase).first
@mentioned_users.push(@user)
replacewith = "<a href='/" + usernotag + "'>*%^$&*)()_+!$" + usernotag + "</a>"
@comment.content = @comment.content.gsub(userwtag, replacewith)
end
@comment.content = @comment.content.gsub("*%^$&*)()_+!$", "@")
Any idea what I should do?
You should use a regular expression to parse/extract the user references:
This assumes your usernames are restricted to alphanumeric characters as you said (letters or numbers). If you have other characters, you can add them to the set included in your regular expression.