Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split based on dynamic variable and keep separator in array

I need to split an array based on a dynamic separator that will change, and keep the separator in the resulting array.

Consider the following example where I need to:

  • Split const match = 'somethingcatsomethingcatsomethingcat'

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • using the separator const separator = 'cat'

  • and get the following array as a result: ["something", "cat", "something", "cat", "something", "cat"].

Here’s what I’ve tried:

const separator = 'cat'
const match = 'somethingcatsomethingcatsomethingcat'

const standardSplit = match.split(separator)
console.log(standardSplit)
// >> Array ["something", "something", "something", ""]

const withPureRegex = match.split(/(cat)/)
console.log(withPureRegex)
// >> Array ["something", "cat", "something", "cat", "something", "cat", ""]
// This is what I need, without the last element of an empty string.
// But I need to pass in the separator dynamically.

const regex = new RegExp(`/(${separator})/`, 'gi')
const withStringLiteral = match.split(regex)
console.log(withStringLiteral)
// >> Array ["somethingcatsomethingcatsomethingcat"]

I’m no good with regex. I’ve read some articles about escaping in regex, but it seems it’s not necessary within RegExp? I tried many variations of the RegExp with no luck.

There are a good number of questions regarding this, but only few I’ve found that attempt to do it with a dynamic separator. The few questions I found had answers using string literals and RegExp like I have above.

If I needed to do this only once, I would use a non-regex approach, like using the first split method above and then manually looping through to insert the separator as needed. But in this case I’m running this match/replace many times and can’t add more overhead if it could be avoided.

>Solution :

You can remove the last empty item using .filter(Boolean).

Demo:

const match = 'somethingcatsomethingcatsomethingcat';
const separator = 'cat';

const reg = new RegExp(`(${separator})`, 'g');
const resArr = match.split(reg).filter(Boolean);

console.log(resArr);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading