Problem with finding proper regular expression in my solution from Codewars task named Mumbling

Viewed 124

I am looking at the Mumbling code challenge on CodeWars:

The examples below show you how to write function accum:

Examples:

accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"

The parameter of accum is a string which includes only letters from a..z and A..Z.

This is my attempt:

function accum(s) {
  const holdArr = [...s];
  const tempArr = [];
  for (let i = 0; i < holdArr.length; i++) {
    tempArr.push(holdArr[i].repeat(i + 1).toLowerCase());
  }
  return tempArr.join("-").replace(/(^|-\w)/g, (x) => x.toUpperCase());
}

The problem is that within input like:

console.log(accum("abCd"));

...it gives output: a-Bb-Ccc-Ddd, but it should give A-Bb-Ccc-Dddd. How can I tune the RegEx to get it?

2 Answers

If you use /(^|-\w)/g, then the letter will be matched only if it follows an hypen.

You should instead use /(^|-)\w/g for matching the letter also when it follows the beginning of the string.

Not a direct answer to the question, but a way to do it without regex:

const accum = (s, c = 0) =>
  [...s.toLowerCase()].map((l) => `${l.toUpperCase()}${l.repeat(c++)}`).join('-');

console.log(accum('abcd')); // A-Bb-Ccc-Dddd

As an aside if you want to find the first word character in a pattern, you can put a word-boundary before it: \b\w. It matches after a - or a the start of the string.

Related