2

I am trying to make a function that takes a string and a delimiter and splits the string it into an array, while keeping the delimiter, using case insensitivity for the search, and preserving original case.

For example, the function signature should look like:

advanced_split("Test Round Start", "St")

And it should return:

["Te", "st", " Round ", "St", "art"]

Note that the splitting is done using case insensitivity, but the case in the original string is preserved in the output array.

Chris Schlitt
  • 133
  • 3
  • 12

2 Answers2

6

This will do it.

function advanced_split(string, delimiter) {
   return string.split(new RegExp(`(${delimiter})`, 'i'));
}

advanced_split("Test Round Start", "St") // ["Te", "st", " Round ", "St", "art"]

It uses a capturing group to extract the delimiter portion of each split, preserving the case. The i flag to a regex means it will be case insensitive.

It's worth pointing out that to make this function more robust, you should use a regex quoting function on the delimiter, otherwise the function may crash on delimiter strings which have special characters in regexs.

alex
  • 479,566
  • 201
  • 878
  • 984
0

The most unoptimized approach would be a nested loop:

 const string = "Test Round Start", find = "St";

 const result = [];

 let acc = "";

 for(let i = 0; i < string.length; i++) {
   var found = true;
   for(let k = 0; k < find.length && k + i< string.length; k++) {
      if(string[k + i] !== find[k]) {
        found = false;
        break;
      }
    }
    if(found) {
      result.push(acc, string.slice(i, k));
      acc = "";
      i += k;
    } else {
      acc += string[i];
   }
 }

 result.push(acc);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151