How to split text into words while only capturing full stops and spaces that come after full stops?

157 Views Asked by At

I would like to split this text,

"Tom works. Tom is a student. Bob is a student."

into this,

["Tom", "works", ".", " ", "Tom", "is", "a", "student", ".", " ", "Bob", "is", "a", "student", "."]

I have tried text.split(/(\.)(\s)/) but I am unsure how to add splitting on spaces without capturing them.

1

There are 1 best solutions below

0
On BEST ANSWER

You can split on non-captured spaces, or on a captured period and optionally captured space, then filter out empty matches:

console.log(
  "Tom works. Tom is a student. Bob is a student."
    .split(/ |(\.)(\s)?/)
    .filter(Boolean)
);

Another method, with .match instead of split, and using lookbehind:

console.log(
  "Tom works. Tom is a student. Bob is a student."
    .match(/[^\s.]+|\.|(?<=\.) /g)
);