2012-10-21 185 views
1

所以我有一段字符串,需要按句點分隔它。我如何得到前兩句話?分割字符串後得到單詞

以下是我有:

var text="Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus." 

text.split("."); 
for (i=0;i <2;i++) { 
    //i dont know what to put here to get the sentence 
} 
+0

感謝所有回答我的問題的 –

+1

可能重複[?如何使用拆分(http://stackoverflow.com/questions/2555794/how-to-use-split) –

回答

0

分割返回數組,所以你需要將它賦值給一個變量。然後,您可以使用數組訪問語法array[0]在該位置得到的值:

var text="Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus." 

var sentences = text.split("."); 
for (var i = 0; i < 2; i++) { 
    var currentSentence = sentences[i]; 
} 
0

它返回一個數組,所以:

var myarray = text.split("."); 

for (i=0;i <myarray.length;i++) { 
    alert(myarray[i]); 
} 
0

split是不使用jQuery混淆,它實際上是一個JavaScript函數返回一個字符串數組 - 你可以在這裏看到的介紹吧:http://www.w3schools.com/jsref/jsref_split.asp

這裏,將使您的示例代碼工作:

var text="Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus." 

// Note the trailing space after the full stop. 
// This will ensure that your strings don't start with whitespace. 
var sentences = text.split(". "); 

// This stores the first two sentences in an array 
var first_sentences = sentences.slice(0, 2); 

// This loops through all of the sentences 
for (var i = 0; i < sentences.length; i++) { 
    var sentence = sentences[i]; // Stores the current sentence in a variable. 
    alert(sentence); // Will display an alert with your sentence in it. 
}​ 
+0

謝謝你你的幫助 –