0

Let's say we have the following strings:

const str1 = 'aabbcc';
const str2 = 'aabbccaaddaaaaeeff';

I need to split them in order to obtain the following result:

mySplitFunction(str1, 'aa')//<--- ['aa','bbcc']
mySplitFunction(str1, 'bb')//<--- ['aa','bb', 'cc']
mySplitFunction(str2, 'aa')//<--- ['aa','bbcc', 'aa','dd', 'aa','aa', 'eeff']
mySplitFunction(str2, 'dd')//<--- ['aabbccaa','dd', 'aaaaeeff']

How would you do it?

5
  • 1
    Consider this answer: Javascript and regex: split string and keep the separator Commented Nov 14, 2021 at 18:10
  • 1
    const mySplitFunction = (str, splitter) => str.split(new RegExp(`(${escapeForRegExp(splitter)})`).filter(s => s) Commented Nov 14, 2021 at 18:13
  • GG for the ones that thought I was asking for a simple split Commented Nov 14, 2021 at 18:15
  • you do, at least given your examples, which is all we got. Commented Nov 14, 2021 at 18:15
  • No bro I wanted to keep the delimiter inside. Thank you btw Commented Nov 14, 2021 at 18:26

2 Answers 2

2

You could take the separator in parenteses and filter the result to omit empty strings.

const
    split = (string, separator) => string
        .split(new RegExp(`(${separator})`))
        .filter(Boolean),
    str1 = 'aabbcc',
    str2 = 'aabbccaaddaaaaeeff';

console.log(...split(str1, 'aa')); // ['aa','bbcc']
console.log(...split(str1, 'bb')); // ['aa','bb', 'cc']
console.log(...split(str2, 'aa')); // ['aa','bbcc', 'aa','dd', 'aa','aa', 'eeff']
console.log(...split(str2, 'dd')); // ['aabbccaa','dd', 'aaaaeeff']

Sign up to request clarification or add additional context in comments.

Comments

2

Try:

const str1 = 'aabbcc';
const str2 = 'aabbccaaddaaaaeeff';
function mySplitFunction(str, delimiter){
  return str.split(new RegExp(`(${delimiter})`)).filter(s => s)
}

console.log(mySplitFunction(str1, 'aa'))
console.log(mySplitFunction(str1, 'bb'))
console.log(mySplitFunction(str2, 'aa'))
console.log(mySplitFunction(str2, 'dd'))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.