views:

72

answers:

2

It's pretty easy to sanitize HTML and strip ALL instances of a HTML tag using Rails helpers...

But how do you just remove ONE tag? In this case, I'm using a WYSIWYG editor that insists on wrapping all my text in a <p> tag. I want to remove this parent tag without stripping out any other <p> tags within the content of the text.

I know I could do this in JQuery really easily but I feel like this should be done server-side in my controller before I save the text.

Is there a way to do this?

+2  A: 

Is your text just always wrapped in a single <p>...</p> block? If so, just substring it.

new_text = text[3, text.length - 7]
Randy Simon
Yes it is... but this feels a bit hacky so I was just wondering if there was a better way...
Ganesh Shankar
+1  A: 

Use regular expressions, i.e.

text.gsub(/(^[ ]*<p>[ ]*)|([ ]*<\/p>[ ]*$)/, '')

Removes the leading and trailing spaces around beginning and ending <p> tag.

E.g:

text = "<p> <div><p>Hello World</p></div> </p>"
#=> "<div><p>Hello World</p></div>"

text = "        <p> <p>Hello World</p> </p>   "
#=> "<p>Hello World</p>"
KandadaBoggu
won't that remove all the <p> tags within the text?
Ganesh Shankar
It does not as `^` and `$` limits it to the first and last `<p>` tag.I have updated the code to remove the leading and trailing spaces also.
KandadaBoggu
Awesome! Thanks a bunch :)
Ganesh Shankar