2012-06-01 28 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); 
相关问题