简体   繁体   中英

Removing the leading and trailing newline characters

I am saving a text along with html tags. For eg, 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.

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

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>/,'')

Rails有一个很好的字符串方法叫做: squish它也会从字符串的中间删除新的行字符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM