2012-06-01 20 views
2

我試圖提取兩句了一堆段落,而我堅持......基本上,段落是這樣的:如何用jQuery提取單個句子?

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

我該怎麼做?

回答

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]); 
+0

這只是一個基本的想法 –

+0

似乎不起作用http://jsfiddle.net/mVrf你/我錯過了什麼? –

+1

你錯過了jquery =)) –

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/

只是要清楚,這criptic聲明snt[+(snt[0].length <= snt[1].length)] = s;意味着,如果我已經有兩句話,然後填充數組你找到下一個將被儲存在地方的snt[0]如果snt[1]是最短的,反之亦然

+0

+1好的解決方案!但爲什麼你需要'~~'?是的,並檢查演示鏈接。 – VisioN

+0

我只是想顯式地將布爾轉換爲數組的索引(0或1) – fcalderan

+0

嗯,或許'+'可能比數字截斷的快捷鍵更適合於類型轉換。但這是一個小問題。 – VisioN

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); 
相關問題