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 a string into substrings that are sandwiched or separated by the same letter in JavaScript?

I have this string:

const str = "abbbaba";

I am looking for a way to split this string in groups of sandwiched letters, or all remaining letters.

Examples

My string should be split into this:

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

["abbba", "ba"]

Where "abbba" is the first substring because it starts and ends with an "a".
The last substring starts with a "b", but there is
no ending "b", so it just takes the rest of the string.

Another scenario:

const str2 = "bbbabaa"

It should be split like this:

["bb", "bab", "aa"]

Closest attempt

The following is my closest attempt for string "abbabbabba" which returns
["abba", "bb", "a", "bb", "a"]
instead of
["abba", "bb", "abba"]

function splitSandwichedLetters(str) {
  const result = [];
  let start = 0;

  for (let i = 1; i < str.length; i++) {
    if (str[i] === str[start] && (i === str.length - 1 || str[i + 1] !== str[start])) {
      result.push(str.slice(start, i + 1));
      start = i + 1;
    }
  }

  if (start < str.length) {
    result.push(str.slice(start));
  }

  return result;
}

// Test 
const str1 = "abbabbabba";


console.log(splitSandwichedLetters(str1)); // Output: ["abbba", "ba"]

>Solution :

In the iteration following a slice – i will be equal to start, and that breaks things because you’ll be checking to see if a letter is equal to itself instead of equal to a letter occurring later. Fix it by incrementing i when you do a slice.

function splitSandwichedLetters(str) {
  const result = [];
  let start = 0;

  for (let i = 1; i < str.length; i++) {
    if (str[i] === str[start]) {
      result.push(str.slice(start, i + 1));
      start = i + 1; // this means that next iteration i will be equal to start
      i++; // so increment i to avoid that
    }
  }

  if (start < str.length) {
    result.push(str.slice(start));
  }

  return result;
}

// Test 
const str1 = "abbabbabba";


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