【发布时间】:2012-06-03 16:31:31
【问题描述】:
例如我有一个带有标记的字符串(来自 html 节点):
hello, this is dog
"h<em>e<strong>llo, thi</strong>s i</em><strong>s d</strong>og"
在其中找到一些单词(比如说“hello”和“dog”)、将它们包裹在一个 span 中(突出显示)并保存所有标记的最正确方法是什么?
所需的输出是这样的(注意正确关闭的标签)
<span class="highlight">h<em>e<strong>llo</strong></em></span><strong>,</strong> <em><strong>thi</strong>s<em> i</em><strong>s <span class="highlight"><strong>d</strong>og</span>
看起来应该是一样的:
hello, this is dog
【问题讨论】:
-
'保存所有标记'在哪里?
-
这不是微不足道的,取决于浏览器支持什么。我知道的最好的方法是使用Range 对象。
-
我不是在谈论浏览器高亮,这只是一个例子。我所需要的只是我的话周围的一些 html 元素包装器
-
给定
hel<b>lo world</b>并且要换行的是“hello”——它应该返回什么? -
hello world 突出显示“你好”
标签: javascript html parsing