Javascript RegExp for splitting text into sentences and keeping the delimiter

daktau picture daktau · Aug 1, 2012 · Viewed 25.3k times · Source

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?

Answer

Larry Battle picture Larry Battle · Aug 1, 2012

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);