1

So I have a paragraph of string and need to separate it by period. How do I get the first 2 sentence?

Here is what I have :

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
}
Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Chad D
  • 499
  • 1
  • 10
  • 17

4 Answers4

0

Split returns an array, so you need to assign that to a variable. You can then use the array accessor syntax array[0] to get the value at that position:

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];
}
Laurence
  • 1,673
  • 11
  • 16
0

It returns an array, so :

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

for (i=0;i <myarray.length;i++) {
    alert( myarray[i] );
}
gogoprog
  • 613
  • 4
  • 7
0

First two sentences should be:

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

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

split isn't to be confused with jQuery, it's actually a JavaScript function that returns an array of strings - you can see an introduction to it here: http://www.w3schools.com/jsref/jsref_split.asp

Here's the code that would make your example work:

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.
}​
alexpls
  • 1,914
  • 20
  • 29