I have a string, and a string I want to match against:
var extendedText = "the Quick Brown Fox Jumps Over the Lazy Dog"
var matchText = "the"
var regex = new RegExp(`(?=[^.*${matchText}.*$])|(?<=[^.*${matchText}.*$])`);
var splitText = extendedText.split(regex);
I want to split the string, keeping the delimiter and end up with something like this:
'the',
' quick brown fox jumps over '
'the'
' lazy dog'
The Regex above currently splits out every character however, giving me this:
'the', '', ' ', '', 'q', '', 'u', '', 'i', '', 'c',........'r', '', ' ', '' 'the', '' ' ' '' 'l', '','a'........etc etc
How can I stop the non-matching text from being split out into a list of characters and instead return a list of the substrings? Or is there a better way to do this altogether?
2
Answers
Change your regex to,
And this will work as you desire.
Also, if you don’t want your match text to match partially, then use b and change your regex to,
Here is a split solution that uses a capture group:
filter(Boolean)
has been used to filter out empty results from array.