如何用jQuery提取单个句子?

时间:2012-06-01 08:39:54

标签: javascript jquery split

我试图从一堆段落中提取两个句子,我被卡住了...基本上,段落看起来像这样:

<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>

我该怎么做?

3 个答案:

答案 0 :(得分:3)

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>
 */

示例小提琴:http://jsfiddle.net/4La9y/2/

为了清楚起见,这个有问题的陈述snt[+(snt[0].length <= snt[1].length)] = s;意味着如果我已经用两个句子填充了数组,那么如果snt[0],您找到的下一个将被存储在snt[1]的位置是最短的,反之亦然

答案 1 :(得分:2)

//First grab all text

var t = $('.some_paragraph').text();
var sentences = t.split('.');
sentences.sort(function(a, b) {
    return a.length - b.length;
});
//sortest sentence
$('.span1').text(sentences[1]);
$('.span2').text(sentences[2]);

答案 2 :(得分:0)

var smallest = 0;
            var smaller = 0;
            var bigger = 0;
            var smallest_sen;
            var smaller_sen;

            $('p.some_paragraph').each(function(){
                plength = $(this).text().length;
                if(smallest == 0){
                smallest = plength;
                smallest_sen = $(this).text();
                }else if(smallest > plength){
                    smaller_sen = smallest_sen;
                    smaller = smallest;
                    smallest = plength;
                    smallest_sen = $(this).text();
                }
            });
            alert(smallest_sen);
            alert(smaller_sen);
相关问题