get sentences in a string in typescript

You can use a regular expression to split a string into an array of sentences based on the punctuation marks (. , ! ?). Here's an example implementation:

index.ts
const text: string = "This is a sample text. It contains multiple sentences! Can you split them? Yes you can.";

const sentences: string[] = text.split(/[\.\?!]/).filter(sentence => sentence.trim() !== '');

console.log(sentences);
// Output: ["This is a sample text", "It contains multiple sentences", "Can you split them", "Yes you can"]
340 chars
7 lines

In this example, we first define the input text as a string. Then, we split the text using a regular expression that matches any of the punctuation marks followed by a whitespace character. We also apply a filter to remove any empty or whitespace-only strings that may result from the split. Finally, we log the resulting array of sentences to the console.

Note that this implementation assumes that each sentence ends with a valid punctuation mark followed by a whitespace character. If your input text contains non-standard or incomplete sentences, you may need to adjust the regular expression or apply additional error checking.

gistlibby LogSnag