2012-06-01 6 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를 작동하지 않을 것 snt[1] 인 경우 내가 잃어버린거야? –

+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]는 짧은 반대의 경우도 마찬가지

+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); 
관련 문제