0

I'm new to JavaScript. I have a text with several sentences and I want each sentence to be an entry in a array named sentences and alert("new entry was made"). So I have to loop through and whenever there is a "." a new entry would start. But How can I go through a text till its end?

var sentences = []
var myText= "I like cars. I like pandas. I like blue. I like music."
BenMorel
  • 34,448
  • 50
  • 182
  • 322
daisy
  • 615
  • 2
  • 8
  • 15
  • 1
    Would [`.split(".")`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split) do it? – Bergi Apr 07 '13 at 12:45
  • What if `myText = "I like cars which cost $19000.00. I like pandas";`? Or `myText = "Mr. Brown likes pandas. I like Mr. Brown.";` – Michael Berkowski Apr 07 '13 at 12:45
  • "*go through a text till its end*" - how do you want to go through it, iterate it character by character or what? – Bergi Apr 07 '13 at 12:46
  • @MichaelBerkowski: I think such cases are out of the scope of this question, OP wants to learn about basic JS string functions. – Bergi Apr 07 '13 at 12:47
  • @Bergi If it's purely academic then maybe out of scope. But if this is for an actual implementation, it needs to be considered. – Michael Berkowski Apr 07 '13 at 12:47

4 Answers4

2

You can do it by splitting myText on ". " and then trimming and adding back the full stop.

jsFiddle

var myText = "I like cars. I like pandas. I like blue. I like music."
var sentences = myText.split(". ");
for (var i = 0; i < sentences.length; i++) {
    if (i != sentences.length - 1)
        sentences[i] = sentences[i].trim() + ".";
}

Splitting the text on ". " instead of on "." will mean it will work on sentences like "That costs $10.50."

Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
2

Use String.charAt(index).

var sentences = [""];
var count = 0;
for(var i = 0; i < myText.length; i++){
    var current = myText.charAt(i);
    sentences[count] += current;
    if(current == "."){
        count++;
        sentences[count] = "";
    }
}
PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
1

You can use split

var myText= "I like cars. I like pandas. I like blue. I like music.";
var sentences  = myText.split(".");
Anoop
  • 23,044
  • 10
  • 62
  • 76
1

While @Pietu1998's answer shows you how to loop through the characters of a string, the more comfortable way of getting an array of sentences from such a string is by matching with a regular expression:

var myText= "I like cars. I like pandas. I like blue. I like music.";
var sentences = myText.match(/\S[^.]*\./g) || [];

Of course this just splits the string on every dot, in real-life not every sentence ends with a dot and not every dot terminates a sentence.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375