1

I want to convert the URL string into an HTML link element (<a href="#"></a>) (like Facebook make with his URLs in the text by example)

I tried this solution Convert links from a string to clickable links using Ruby/Rails but I just get some HTML link in plain text...

Example :

I have this

string = "blabla http//www.google.com blabla
lorem ipsum lorem ipsum"

And I would this, not in plain text but as HTML element

<p>blabla</p> 
<a href="http//www.google.com">http//www.google.com</a> 
<p>blabla</p>
<p>lorem ipsum lorem ipsum</p>

Thank you for your help :)

2

2 Answers 2

0

the plain text can be converted to html by called html_safe method on string. Like '<a href="http//www.google.com">http//www.google.com</a>'.html_safe

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

1 Comment

Thank you I don't know why it's not working from controller but it's working from view. But I have another question how prevent javascript code like <script>alert('hello')</script> How just passing http url as html_safe ?
0

I would split the input into "words", compare each word with a regex for a url, and if it matches, wrap it in a link element.

In this answer I'll just use a simple regex. We'll consider anything starting with http:// or https:// to be a URL. You can use something more advanced if you like.

string = "blabla https://www.google.com blabla lorem ipsum lorem ipsum"

string = string.split.map do |word|
  if /https?:\/\/.*/.match word
    next "<a href=\"#{word}\">#{word}</a>"
  else
   next word
  end
end.join(' ')

puts string #=> blabla <a href="https://www.google.com">https://www.google.com</a> blabla lorem ipsum lorem ipsum

Note that this doesn't actually work with the original string in your answer, because it's not a valid url (it's missing the colon).

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.