我试图从一堆段落中提取两个句子,但我陷入困境......基本上,这些段落看起来像这样:
<p class="some_paragraph">This is a sentence. Here comes another sentence. A third sentence.</p>
<p class="some_paragraph">Another sentence here. Interesting information. Very interesting.</p>
<p class="some_paragraph">This is a sentence. Here comes another sentence. A third sentence.</p>
我需要做的是从这三个段落中的所有 9 个句子中找到两个“最短”的句子。提取的两个句子必须放入以下范围内:
<span class="span1">Shortest sentence comes here</span>
<span class="span2">Second shortest sentence comes here</span>
我该怎么做?
最佳答案
var snt = [];
$('.some_paragraph').each(function() {
var text = $(this).text();
text.replace(/[A-Z][^.]+\./g, function(s) {
if (snt.length < 2) {
snt.push(s);
}
else {
snt[+(snt[0].length <= snt[1].length)] = s;
}
});
});
console.log(snt); // outputs the two shortest sentences
/* creating two span with shortest sentences */
snt.map(function(el, i) {
$('<span />', { class: "span" + (i+1), text: el }).appendTo($('body'));
});
/**
* Result:
*
* <span class="span1">Very interesting.</span>
* <span class="span2">A third sentence.</span>
*/
fiddle 示例:http://jsfiddle.net/4La9y/2/
需要明确的是,这个关键声明 snt[+(snt[0].length <= snt[1].length)] = s;
意味着如果我已经用两个句子填充了数组,那么您找到的下一个将存储在 snt[0]
的位置如果snt[1]
是最短的,反之亦然
关于javascript - 如何使用 jQuery 提取单个句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10847031/