我试图用跨度标记来包装给定文本的单个句子,到目前为止,这是相当不错的。
$this.html().replace(/\b.*?[\.\?\!]/gi, "<span>$&<\/span>");
现在,在内容中已经出现了一些其他的span和b标记,如下所示:
Gumbo groundnut daikon radicchio scallion lettuce rock melon peanut. <span class="yellow">Catsear swiss chard epazote bush tomato peanut chicory amaranth tomato gourd.</span> Earthnut pea brussels sprout gumbo celery tomato salad kale. Spinach scallion tomatillo bitterleaf lentil <b>green</b> bean celery amaranth onion catsear sweet pepper fava bean silver beet spinach.
由于我不想去掉这些标记,也不想封装它们,所以解决方案可以是:
最后它看起来会是这样的:
<span>Gumbo groundnut daikon radicchio scallion lettuce rock melon peanut. <span class="yellow">Catsear swiss chard epazote bush tomato peanut chicory amaranth tomato gourd.</span> <span>Earthnut pea brussels sprout gumbo celery tomato salad kale.</span> <span>Spinach scallion tomatillo bitterleaf lentil </span><b>green</b><span> bean celery amaranth onion catsear sweet pepper fava bean silver beet spinach.</span>
这样的正则表达式会是什么样子?我对此感到非常头痛,因为我的判断力还很有限。
发布于 2013-01-02 17:53:24
编写解析器,而不是正则表达式。要处理嵌套的HTML标记将非常困难,例如,只使用正则表达式。
发布于 2013-01-04 09:40:32
我现在已经实现了一个小功能,它或多或少地实现了我想要的功能。它基本上取代了所有的孩子(跨度,b,等等)使用占位符-元素,这样它们就不会弄乱正则表达式。稍后,我只需将占位符替换为原始子元素。这是一种快速而肮脏的解决方案,但就目前而言,它已经足够有效了。
function wrapSentences($element){
var j = 0, i = 0, placeholders = [];
$.each($element.children(),function(){
var p = $("<b id='p"+j+"'></b>");
$(this).after(p).remove();
placeholders.push($(this));
j++;
});
$element.html($element.html().replace(/\(?[A-Z][^\.]+[\.!\?]\)?/g, "<span class='s'>$&<\/span>"));
$.each(placeholders,function(){
$element.find("#p"+i).replaceWith(this);
i++;
});
}jsFiddle
https://stackoverflow.com/questions/14126673
复制相似问题