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

How to split one string including it in the array javascript?

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?

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

>Solution :

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']
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