首页 > 解决方案 > 如何在ruby中将最后一个可用空间替换为nbsp

问题描述

如何将最后一个可用空间替换 ruby​​ ?

我在数据库中有这个:

<h1>Hello dear friend!</h1>
<p>How are you?</p>
<figure><img src="..." alt="..." /></figure>
<p>Bye!</p>

我需要有这个“输出”:

<h1>Hello dear&nbsp;friend!</h1>
<p>How are&nbsp;you?</p>
<figure><img src="..." alt="..." /></figure>
<p>Bye!</p>

我试着和 nokogiri 一起玩:

text = Nokogiri::HTML::DocumentFragment.parse(...)
text.css('h1, h2, h3, h4, h5, h6, p, li').each do |tag|
  tag_arr = tag.content.split(' ')
  tag_last_words = tag_arr[tag_arr.length-2..tag_arr.length]
  tag_return = tag_arr[0..-2].push(tag_last_words.join('&nbsp;'))
  tag_return = tag_return.join(' ')
  tag.content = tag_return
end

但我无法击败一些“错误”:


为什么?避免在移动设备上换行换行。(在我的情况下,JS 不是一个选项)

标签: ruby-on-railsparsing

解决方案


推荐阅读