Question

How can I remove whitespace from within html tags?

For example:

"\r\n\t This is a paragraph\r\n".strip
=> "This is a Paragraph"

But what about when:

"<p>\r\n\t This is a paragraph\r\n</p>".strip
=> "<p>\r\n\t This is a paragraph\r\n</p>"

How can I get ruby to remove the whitespace from inside the

tags (while retaining the p tags)?

Was it helpful?

Solution

In rails , there is a method name 'squish', for example:

"<p>\r\n\t This is a paragraph\r\n</p>".squish => "<p> This is a paragraph </p>"

Returns the string, first removing all whitespace on both ends of the string, and then changing remaining consecutive whitespace groups into one space each.

It leaves a space. If you want to get "<p>This is a paragraph</p>", I think you should use regex , it's more complicated than this. ^_^

OTHER TIPS

If you want to use it in view. You can do with the below statement.

<%= strip_tags("<p>\r\n\t This is a paragraph\r\n</p>").strip %>

suppose if you want to use it in controller you can do with this statement.

self.class.helpers.strip_tags("<p>\r\n\t This is a paragraph\r\n</p>").strip

strip_tags method will removes all html tags from string.

I hope this will helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top