1

所以我有一段字符串,需要按句点分隔。我如何得到前2句话?

这是我所拥有的:

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
}
4

4 回答 4

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.
}​
于 2012-10-21T21:39:19.710 回答
0

Split 返回一个数组,因此您需要将其分配给一个变量。然后,您可以使用数组访问器语法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];
}
于 2012-10-21T21:27:28.313 回答
0

它返回一个数组,所以:

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

for (i=0;i <myarray.length;i++) {
    alert( myarray[i] );
}
于 2012-10-21T21:27:38.123 回答
0

前两句应该是:

 text.split('.').slice(0,2).join('. ');

JS 小提琴演示

参考:

于 2012-10-21T21:29:24.250 回答