2

一連の段落から2つの文を抽出しようとしていますが、行き詰まっています...基本的に、段落は次のようになります。

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

私がする必要があるのは、これらの3つの段落の9つの文すべてから2つの「最短」の文を見つけることです。抽出された2つの文は、次のスパンに入れる必要があります。

<span class="span1">Shortest sentence comes here</span>
<span class="span2">Second shortest sentence comes here</span>

それ、どうやったら出来るの?

4

3 に答える 3

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;は、配列が既に 2 つの文で満たされている場合、次に見つかった文がsnt[0]if snt[1]is shortest の代わりに保存され、その逆も同様であることを意味します。

于 2012-06-01T08:52:20.713 に答える
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]);
于 2012-06-01T08:48:57.380 に答える
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);
于 2012-06-01T08:57:50.147 に答える