分割字符串后获取单词

时间:2012-10-21 21:23:53

标签: javascript

所以我有一段字符串,需要按句点分隔。我怎么得到前两个句子?

这就是我所拥有的:

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 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:0)

它返回一个数组,所以:

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

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

答案 2 :(得分:0)

前两句应该是:

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

JS Fiddle demo

参考文献:

答案 3 :(得分: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.
}​