将简单文本转换为html格式的换行符和制表符

时间:2019-05-08 08:33:18

标签: ruby-on-rails ruby ckeditor4.x

编写一种将简单文本文件转换为html的方法,以便可以将其集成到ckeditor中。但是,我们无法使用任何RoR gem转换空格,制表符和换行符

我尝试过

output_html = ActionController::Base.helpers.simple_format(contents)
output_html = output_html.gsub(/ (?= )/, ' ')
text_content = "firstline\nsecond   line \n\n\nthird line\t\taftertab"

output_html = "firstline<br/>second&nbsp;&nbsp;line<br/><br/><br/>third<br/>line&nbsp;&nbsp;&nbsp;&nbsp;aftertab"

1 个答案:

答案 0 :(得分:2)

您可以使用String.gsub

text_content = "firstline\nsecond   line \n\n\nthird line\t\taftertab"

text_content.gsub(/\s/, "\n" => "<br/>", "\t" => "&nbsp;&nbsp;", " " => "&nbsp;")
# => "firstline<br/>second&nbsp;&nbsp;&nbsp;line&nbsp;<br/><br/><br/>third&nbsp;line&nbsp;&nbsp;&nbsp;&nbsp;aftertab"