const regex = /^.{0,79}?(?=\.(?:$| [A-Z]))\..+?(?=\.(?:$| [A-Z]))\.|^.{80,}?(?=\.(?:$| [A-Z]))\./gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^.{0,79}?(?=\\.(?:$| [A-Z]))\\..+?(?=\\.(?:$| [A-Z]))\\.|^.{80,}?(?=\\.(?:$| [A-Z]))\\.', 'gm')
const str = `First sentence; if first sentence <80 chars, get first 2 sentences.
The temperature was 32.8 degrees Celsius, his B.Sc. degree was deemed insufficient. The Dr. owed B. the bank USD 4000.50 which he had not paid back. On 27.07.2004 a major earthquake occurred. It was 17.05 by the clock.
First sentence if >80 chars, else get first 2 sentences if first sentence <80 chars
The temp was 32.8 C. His B.Sc. was insufficient.`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions