2013-06-20 27 views
0

使用javascript和jquery我試圖分開句子,並將它們逐個存儲到數組中。這是我試過的我該如何將單獨的類一個接一個地分配到一個數組中?

var sentenceArray = new Array(); 

//SPLITS PARAGRAPHS INTO SENTENCES// 
$('#text').each(function() { 

    var sentences = $(this).html().replace(/([^.!?]*[^.!?\s][.!?]['"]?)(\s|$)/g,'<span class="sentence">$1</span>$2'); 
        sentenceArray.push(sentences); 

}); 

但是,這返回所有組合到數組的索引中的句子。我如何區分它們?

<div id="text"> 

    Crowds blocked main roads in Sao Paulo and Brasilia, and protesters confronted police in Rio de Janeiro state shortly after the U-turn was announced. 
    Earlier, there were clashes before Brazil's football team played Mexico in Fortaleza in the Confederations Cup. 
    Protesters are angry at corruption and high spending on next year's World Cup. 
    Activists say they have not changed their intention to hold the biggest demonstrations yet on Thursday. 
    The BBC's Julia Carneiro, in Sao Paulo, says hundreds of thousands are expected on the streets there before another round of matches in the Confederations Cup. 

</div> 
+0

這是什麼文字的樣子? – adeneo

+0

像這樣:此前,在巴西足球隊在聯合會杯的福塔萊薩隊打墨西哥隊之前發生衝突。 抗議者對於明年世界盃的腐敗和高消費感到憤怒。 活動人士說,他們並沒有改變他們打算在週四舉行最大規模的示威遊行的意圖。 Squirrl

+0

如果所有的句子都與換行符分開,也就是說,在句子結尾處輸入了句子,你可以分割新行嗎? – adeneo

回答

0

你可以像這樣做,請看:

var sentenceArray = new Array(); 

//SPLITS PARAGRAPHS INTO SENTENCES// 
var sentences = $(this).html().replace(/([^.!?]*[^.!?\s][.!?]['"]?)(\s|$)/g,'<span class="sentence">$1</span>$2<SENTENCE_END>'); 

sentenceArray = sentences.split("<SENTENCE_END>"); 

這將是可能的情況下,你可以更改您的正則表達式。

+0

這似乎工作,但出於某種原因,我的CSS。語句不再適用於樣式..? – Squirrl

+0

@Squirrel我看不到這個原因。我們甚至不更新你的文本容器。可能你在這之後添加了一些有問題的代碼?像'$(this).text(句子)''? – Cherniv

+0

帶來了所有的HTML前面。 '$(本)的.html(句子);'作品並添加了所有樣式,但是SENTENCE_END在每個句子後都顯示在文本的前面。 – Squirrl

0

您的數組對象定義錯誤。試試這個例子:

var array = []; 
    array.push('one'); 
    array.push('two'); 
    alert(array[0]); 
    alert(array[1]); 
相關問題