Question

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."
Was it helpful?

Solution

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."

OTHER TIPS

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] = "";
    }
}

You can use split

var myText= "I like cars. I like pandas. I like blue. I like music.";
var sentences  = myText.split(".");

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top