【问题标题】:Wrap words in tags, keep markup用标签包裹单词,保留标记
【发布时间】: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&lt;b&gt;lo world&lt;/b&gt; 并且要换行的是“hello”——它应该返回什么?
  • hello world 突出显示“你好”

标签: javascript html parsing


【解决方案1】:

给你:

//Actual string
var string = "h<em>e<strong>llo, thi</strong>s i</em><strong>s d</strong>og";

//RegExp to cleanup html markup
var tags_regexp = /<\/?[^>]+>/gi;

//Cleaned string from markup
var pure_string = string.replace(tags_regexp,"");

//potential words (with original markup)
var potential_words = string.split(" ");

//potential words (withOUT original markup)
var potential_pure_words = pure_string.split(" ");

//We're goin' into loop here to wrap some tags around desired words
for (var i in potential_words) {

    //Check words here
    if(potential_pure_words[i] == "hello," || potential_pure_words[i] == "dog")

    //Wrapping...
    potential_words[i] = "<span class=\"highlight\">" + potential_words[i] + "</span>";
}

//Make it string again
var result = potential_words.join(" ");

//Happy endings :D
console.log(result);

【讨论】:

  • 不是真正的优化解决方案,但您知道,它仍然有效。我困了,自己优化吧:D
  • 出现问题:标签关闭和打开顺序错误:'hello,'
  • @spacevillain 嗯,没注意到,但您需要在这里做一些澄清,以便我可以修复它: 1- 在您的原始字符串中, 是在“s i”之后,但在您更正的字符串中,它在“llo”之后。 为什么? 2- 如果我对上一个问题的回答是基于逻辑的,那么您的更正字符串的其余部分是否还有逻辑? 3- 如果它不是逻辑,那么可能是一个错字,所以你应该找到一种方法来以编程方式更正你的标记,然后看看 Chromium 项目的源代码,它会帮助你编写一些为此目的的标记清理器/校正器。
猜你喜欢
  • 2013-05-09
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多