Search code examples
javascriptregexsentence

Javascript RegExp for splitting text into sentences and keeping the delimiter


I am trying to use javascript's split to get the sentences out of a string but keep the delimiter eg !?.

So far I have

sentences = text.split(/[\\.!?]/);

which works but does not include the ending punctuation for each sentence (.!?).

Does anyone know of a way to do this?


Solution

  • You need to use match not split.

    Try this.

    var str = "I like turtles. Do you? Awesome! hahaha. lol!!! What's going on????";
    var result = str.match( /[^\.!\?]+[\.!\?]+/g );
    
    var expect = ["I like turtles.", " Do you?", " Awesome!", " hahaha.", " lol!!!", " What's going on????"];
    console.log( result.join(" ") === expect.join(" ") )
    console.log( result.length === 6);