11

I want regular expression in ruby on rails which remove all the html tags and its content from the given text.

For example if my text is :-INPUT :-

<span id="span_is"><br><br><u><i>Hi</i></u></span> 

then it should display only OUTPUT should be as follows:-

Hi

in short i want regular expression or a function which remove <> and whatever the content between <>.

Thanks & Regards,

Salil Gaikwad

1
  • I found a solution. I have posted the regex here Commented Nov 1, 2022 at 13:00

3 Answers 3

19
'<span id="span_is"><br><br><u><i>Hi</i></u></span>'.gsub(/<\/?[^>]+>/, '')
Sign up to request clarification or add additional context in comments.

1 Comment

Although the accepted answer is the most elegant way to go, this solution actually suits my needs better. Thank you!
15

Your string is quite simple and that solution might work. However, you shouldn't reinvent the wheel. Rails already includes some powerful sanitization helpers.

string = '<span id="span_is"><br><br><u><i>Hi</i></u></span>'
strip_tags(string)

1 Comment

just to add, it does not removes characters like &nbsp; :)
1

Don't do this. Please.

While your sample-input is fairly trivial, you mention that you want to use it in a lot broader scope.

http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html

For Ruby, you can try using http://hpricot.com/ to parse HTML instead.

1 Comment

Actually i need to solve my problem that in my mail when i view as a text it shows html tags.So i replace my chat.text.plain.erb with following as answered by jimmy <%= @chat.gsub(/<\/?[^>]+>/, '') %> and it works for me . anyways thanks for your comment. Salil

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.