Home > database >  String parsing, parse a string and generate array of sub-string like example given
String parsing, parse a string and generate array of sub-string like example given

Time:10-15

Input: United States America

Output: [United, States, America, States America, United States, United States America]

CodePudding user response:

function splitAndRecombine(value) {
  return String(value)
    .split(/\s /)
    .reduce((result, item, idx, arr) => {
      const rest = arr.slice(idx);

      result.push(rest.join(' '));

      while (rest.pop() && rest.length >= 1) {
        result.push(rest.join(' '));
      }
      return result;
    }, []);
}

console.log(
  "splitAndRecombine('United States America') ...",
  splitAndRecombine('United States America')
);
console.log(
  "splitAndRecombine('United States of America') ...",
  splitAndRecombine('United States of America')
);
console.log(
  "splitAndRecombine('United Kingdom of Great Britain and Northern Ireland') ...",
  splitAndRecombine('United Kingdom of Great Britain and Northern Ireland')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

  • Related