The idea here is we build a RegExp using your input d
. In the end we want it to look like -
const reLiteral =
/[.;:?!](?= )/
To make the matches appear in .split
output, we add (...)
around the entire pattern
const reLiteralWithCapture =
/([.;:?!](?= ))/
However since we will be building the RegExp from an array of strings, we need to use the new RegExp(...)
constructor -
const d =
[ ".", ";", ":", "?", "!" ]
const re =
new RegExp(`([${d.join()}](?= ))`)
Here it is in a sample program -
const str =
"Don't forget, you will have to pay $4.10! That's the going rate for a good apple nowadays; not a bad rate to be honest. What, you don't think so? We can agree to disagree. No? Fine we will disagree to agree then."
const d =
[ ".", ";", ":", "?", "!" ]
const re =
new RegExp(`([${d.join()}](?= ))`)
const parts =
str.split(re)
console.log(parts)
Whether that matches your exact needs is unknown to me. Hopefully it's enough to get you started and show you where you can make the necessary changes to finish the problem.