Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS split text into sentences

I want to receive a lot of text (e.g. a book chapter), and create an array of the sentences.

My current code is:

text.match( /[^\.!\?]+[\.!\?]+["']?/g );

This only works when the text ends with one of [. ! ?]. If the final sentence has no punctuation at the end, it's lost.

How do I split my text into sentences, allowing for the final sentence to not have punctuation?

like image 795
Mirror318 Avatar asked Oct 17 '25 22:10

Mirror318


1 Answers

Use $ to match the end of the string:

/[^\.!\?]+[\.!\?]+["']?|.+$/g

Or maybe you want to allow whitespace characters at the end:

/[^\.!\?]+[\.!\?]+["']?|\s*$/g
like image 53
David Knipe Avatar answered Oct 19 '25 12:10

David Knipe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!