Split string by every new instance of a letter

Viewed 67

Couldn't find anything while searching but I need to split a string by each new instance of a letter. I know split() would output: (M,B,A,M,M,D,X,X,M,M,M,G,G,M,M,Z) but can't figure out how to group them.

Exmaple: "MBAMMDXXMMMGGMMZ" should output to: M B A MM D XX MMM GG MM Z

str = "MBAMMDXXMMMGGMMZ"

newStr = str.split("")
console.log(newStr)

2 Answers

One regex approach would be to do the following find and replace:

Find:    (.)(?!\1)
Replace: $1[ ]

This regex pattern will capture each letter which is not followed by the same letter, and in that case insert a space after the captured letter:

(.)    capture each letter
(?!\1) which is NOT followed by the same letter (i.e. is followed by a different letter)

Sample script:

var input = "MBAMMDXXMMMGGMMZ";
var output = input.replace(/(.)(?!\1)/g, "$1 ");
console.log(input + "\n" + output);

If you'd like to avoid regular expressions you may convert the string into an array and use the reduce method.

var input = "MBAMMDXXMMMGGMMZ";

Array.from(input).reduce((prev, curr, index, array) => {
  let next;
  if (prev.includes(curr)) {
    // If char matches previous group, add it.
    next = prev + curr;
  } else {
    // If it differs, log previous group and begin a new one.
    console.log(prev);
    next = curr;
  }
  
  // If that's the last iteration, log the final group.
  if (index == array.length - 1) {
    console.log(next);
  }
  
  return next;
});

It is also possible to use this method to get an array of grouped string, it just requires changing the console logging to pushing groups into some array.

var input = "MBAMMDXXMMMGGMMZ";
var output = [];

Array.from(input).reduce((prev, curr, index, array) => {
  let next;
  if (prev.includes(curr)) {
    // If char matches previous group, add it.
    next = prev + curr;
  } else {
    // If it differs, add previous group to an output array and begin a new one.
    output.push(prev);
    next = curr;
  }
  
  // If that's the last iteration, push the final group.
  if (index == array.length - 1) {
    output.push(next);
  }
  
  return next;
});

console.log(output);

Related