Rajesh Omanakuttan
Rajesh Omanakuttan

Reputation: 6918

Removing the leading and trailing newline characters

I am saving a text along with html tags. For e.g., if I enter 'What is your name?', it will be stored as '<p>What is your name?</p>' inside the table.

If take the same value to a report, it has an extra newline at the beginning and at the end of the string. I am outputting the value of @question.description using the code @question.description.html_safe.

Kindly tell me a solution to trim out "\n" from the beginning and from the end of that paragraph string.

Upvotes: 3

Views: 1609

Answers (3)

shweta
shweta

Reputation: 8169

To remove all html tags use strip_tags method

strip_tags('<p>What is your name?</p>')

To remove only starting and ending <p></p> tag

s = ' <p>What is <p> your</p> name?</p> '
s = s.strip.sub('<p>','').chomp('</p>')
#=> "What is <p> your</p> name?"

To remove all <p></p> tags

'<p>What is your name?</p>'.gsub(/<p>|<\/p>/,'')

Upvotes: 1

Benjamin Harel
Benjamin Harel

Reputation: 2946

Rails has a nice method for string called: squish It removes new line characters from the middle of the string too.

Upvotes: 0

oldergod
oldergod

Reputation: 15010

String#strip: Returns a copy of str with leading and trailing whitespace removed.

"\n what\r\n".strip
#=> "what"

If you want to change your variable, you need to do one of the following

s = "\nyour string\n"
s.strip!    # first option
s = s.strip # second option

Upvotes: 5

Related Questions