首页 > 解决方案 > 将简单文本转换为 html 以尊重换行符空格和制表符

问题描述

编写一个将简单文本文件转换为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"

标签: ruby-on-railsrubyckeditor4.x

解决方案


您可以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"

推荐阅读