Search code examples
javascriptstring-searchsplit

JS - go throught a text, make array entry after each "."


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

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