Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: use regex to replace http://anything with <a href="http://anything">http://anything</a>

Tags:

regex

ruby

I've seen a lot of variations on this question, but they usually are trying to either validate the 'anything' portion of the url, or provide different text for the anchor text vs the link.

For a simple blog function for users, I need the application helper that returns the same text except finds any string that starts with http:// (and ends in any whitespace or end of string) and replaces it with a <a href="same_string_here">same_string_here</a>

Any tips on how to do this with regex would be appreciated... I figured out bits and pieces (grab a word starting with http) but cannot get the whole thing to work (can't figure out how to put it into the template with quotes around the href, handle the :// in the test, or put the string in a second place before the </a>).

like image 646
jpw Avatar asked May 03 '26 08:05

jpw


2 Answers

You can try the following approach:

str = "XYZhttp://abc XYZ"
str.gsub!(/(http:\/\/\S+)/, '<a href="\1">\1</a>')
puts str

which will give you

XYZ<a href="http://abc">http://abc</a> XYZ

Note: \S+ captures any non-whitespace, i.e. you have to have at least one such character after http://. It does also not remove the whitespace after http://abc. If you need you can append \s* to the regular expression outside the paranthesis.

like image 111
Howard Avatar answered May 05 '26 08:05

Howard


I think an answer can be extracted from this answer: Turn URLs and @* into links. It does more than you want because it looks for twitter specific links like "@" but it does have solutions to your href question.

like image 44
Ray Toal Avatar answered May 05 '26 10:05

Ray Toal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!