Reputation: 255
I want to find all words that starts @
the character in a string and change it to the <a>
HTML tag.
For example:
my_string = 'Hello @username this is your page'
# in my_string i want replace @username like:
@username => <a href='mysite.com/username'>@username</a>
# expected output =>
Hello <a href='mysite.com/username' >@username</a> this is your page
Thoughts?
Upvotes: 0
Views: 371
Reputation: 564
The answer of mrazza is doing very well the job. But if you want to avoid using regex I guess it could be helpful.
result = []
splitted_string = 'Hello @username this is your page'.split
splitted_string.each_with_index do |a, i|
result << a
if a.include? '@'
result.insert(i, "<a href='mysite.com/username' >", a, "</a>")
.delete_at(i + 3)
end
end
p result.join(' ')
#=> "Hello <a href='mysite.com/username'>@username</a> this is your page"
Basically you split your string to get an array, you iterate over it and if you find an @
you add the element you want between it by using index.
If you don't want to delete an element which can be tricky, you can write the following line between your statement:
result.insert(i, "<a href='mysite.com/username' >")
result.insert(i + 2, "</a>")
Upvotes: 1
Reputation: 23347
You can use String#gsub
with a regex:
my_string = 'Hello @username this is your page'
my_string.gsub(/@(\w+)/,'<a href=\'mysite.com/\1\'>@\1</a>' )
#=> "Hello <a href='mysite.com/username'>@username</a> this is your page"
Regex explanation:
@\w+
in regex means @
and one or more word characters (\w
stands for alphanumerical characters or an underscore)(...)
in regex catches the username in a capturing group, that can be used later in replacements\1
in a second gsub
argument instructs gsub
to put contents of the first capturing group to this place of the string - in this case, the usernameUpvotes: 2