skip to Main Content

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


  1. Change your regex to,

    (?=${matchText})|(?<=${matchText})
    

    And this will work as you desire.

    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);
    
    console.log(splitText);

    Also, if you don’t want your match text to match partially, then use b and change your regex to,

    (?=b${matchText})b|b(?<=${matchText})b
    
    var extendedText = "the Quick Brown Fox there Jumps Over the Lazy Dog"
    var matchText = "the"
    
    var regex = new RegExp(`(?=\b${matchText}\b)|(?<=\b${matchText}\b)`);
    
    var splitText = extendedText.split(regex);
    
    console.log(splitText);
    Login or Signup to reply.
  2. Here is a split solution that uses a capture group:

    var extendedText = "the Quick Brown Fox Jumps Over the Lazy Dog";
    var matchText = "the";
    var arr = 
    extendedText.split(new RegExp(`(\b${matchText}\b)`)).filter(Boolean);
    
    console.log(arr);
    
    /*[
    'the',
    ' Quick Brown Fox Jumps Over ',
    'the',
    ' Lazy Dog'
    ]*/

    filter(Boolean) has been used to filter out empty results from array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search