3

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>).

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

perfect, and a helpful explanation of how it's working, thank you!
I would use \b instead of \S, so you don't consume the whitespace after the URL, and so that it works, for example, at the end of lines.
@Ian I used \S with capital s to match non-whitespaces. Therefore it does not consume whitespaces and there is no problem with end of lines.
2

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.

Comments

0

You can use:

body.gsub(/(?<!"|'|>)https?:\/\/[\S]+/, '<a href="\0">\0</a>').html_safe

The advantage of this approach is it'll replace the text, but not the html link, for example:

https://www.example.com
http://www.example.com
<a href="https://www.example.com">https://www.example.com</a

# becomes

<a href="https://www.example.com">https://www.example.com</a>
<a href="https://www.example.com">http://www.example.com</a>
<a href="https://www.example.com">https://www.example.com</a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.