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?
You need to use match not split.
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);
The following is a small addition to Larry's answer which will match also paranthetical sentences:
text = "If he's restin', I'll wake him up! (Shouts at the cage.) 'Ello, Mister Polly Parrot! (Owner hits the cage.) There, he moved!!!"
["If he's restin', I'll wake him up!", " (Shouts at the cage.)", " 'Ello, Mister Polly Parrot!", " (Owner hits the cage.)", " There, he moved!!!"]
Try this instead:-
sentences = text.split(/[\\.!\?]/);
? is a special char in regular expressions so need to be escaped.
Sorry I miss read your question - if you want to keep delimiters then you need to use
split see this question
A slight improvement on mircealungu's answer:
'!?'etc. are included inside sentences.
Improving on Mia's answer here is a version which also includes ending sentences with no punctuation:
©2020 All rights reserved.