utcghghvgh utcghghvgh - 7 months ago 7
Ruby Question

Insert a string on regex match in ruby

str = "This website is <a href='www.google.com'>Google</a>, some other website is <a href='www.facebook.com'>Facebook</a>"
style_to_add = "style='text-decoration:none;'"


I want to add the
style_to_add
string to every hyperlink. So the result becomes

str = "This website is <a href='www.google.com' style='text-decoration:none;>Google</a>, some other website is <a href='www.facebook.com' style='text-decoration:none;>Facebook</a>"

Answer

This regex will work

(href='[^']+')

Regex Demo

More accurate regex will be to use

(\bhref='[>']+)>

Ruby Code

pattern = %r{(href='[^']+')}
str = "This website is <a href='www.google.com'>Google</a>, some other website is <a href='www.facebook.com'>Facebook</a>"
style_to_add = "style='text-decoration:none;'"
print str.gsub(pattern, '\1 ' + style_to_add)

Ideone Demo