在线转换文本为html,将纯文本列表转换为html

本文介绍了一种使用Haml gem将带有缩进的纯文本转换为有效的HTML列表的方法。通过简单的Ruby脚本,可以解析文本中的缩进并将其转换成HTML列表结构。此方法特别适用于从非结构化的文本数据中快速生成有序或无序的HTML列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

老话题,但......

看起来我找到了一种方法来使Glenn Jackman代码html有效(避免

  • 与孩子
    • )。

我正在使用带缩进缩进的字符串。

require 'haml'

class String

def text2htmllist

tabs = -1

topUL=true

addme=''

haml = self.gsub(/^([t]*)/) do |match|

line_tabs = match.length

if ( line_tabs > tabs )

if topUL

repl = "#{match}#{addme}%uln"

topUL=false

else

repl = "#{match}#{addme}%lin"

addme += "t"

repl += "#{match}#{addme}%uln"

end

else

repl = ''

addme = addme.gsub(/^[t]/,'') if ( line_tabs < tabs ) #remove one t

end

tabs = line_tabs

repl << "t#{match}#{addme}%li "

end

puts haml

Haml::Engine.new(haml).render

end

end #String class

str = <

I am the first top-level list item

I am his son

Me too

Second one here

His son

His daughter

I am the son of the one above

Me too because of the indentation

Another one

FIM

puts str.text2htmllist

生产:

%ul

%li I am the first top-level list item

%li

%ul

%li I am his son

%li Me too

%li Second one here

%li

%ul

%li His son

%li His daughter

%li

%ul

%li I am the son of the one above

%li Me too because of the indentation

%li Another one

I am the first top-level list item
  • I am his son
  • Me too
Second one here
  • His son
  • His daughter
    • I am the son of the one above
    • Me too because of the indentation
  • Another one
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值