2012-10-21 135 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

谢谢你你的帮助 –