I have this string:
JavaScript
x
2
1
var text = 'Hello. World... Lorem? Ipsum 123';
2
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:
JavaScript
1
2
1
text = 'Hello. World... Lorem?';
2
Advertisement
Answer
You could try a regex replacement:
JavaScript
1
3
1
var text = 'Hello. World... Lorem? Ipsum 123';
2
var output = text.replace(/([.?!])(?!.*[.?!]).*$/, "$1");
3
console.log(output);
The replacement logic here says to:
JavaScript
1
6
1
([.?!]) match and capture a closing punctuation
2
(?!.*[.?!]) then assert that this punctuation in fact
3
be the final one
4
.* match and consume all remaining text
5
$ until the end of the input
6
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).