Skip to content
Advertisement

Strip everything after the last sentence [closed]

I have this string:

var text = 'Hello. World... Lorem? Ipsum 123';

Using javascript regex, how can I strip everything that is after the last ., ?, ! (the end of the last sentence).

With the above example, it should result to:

text = 'Hello. World... Lorem?';

Advertisement

Answer

You could try a regex replacement:

var text = 'Hello. World... Lorem? Ipsum 123';
var output = text.replace(/([.?!])(?!.*[.?!]).*$/, "$1");
console.log(output);

The replacement logic here says to:

([.?!])      match and capture a closing punctuation
(?!.*[.?!])  then assert that this punctuation in fact
             be the final one
.*           match and consume all remaining text
$            until the end of the input

Then we replace that final punctuation mark. We could, in theory, have used a lookbehind, but this isn’t supported on all versions of JavaScript (not at least on SO’s demo tool).

Advertisement