I want to count a same letter if the previous letter is the same as the current letter

Viewed 58

I have the input string "lorrem ipsssum dollorrrrum" and I want to count the same letter if the current letter is the same as the previous letter and change all the next same letter to the counted that letter,

I want the exact result to look like this:

"lor2emips3umdol2or4um"

I am stuck and I don't know what algorithm should I use, and what keyword to search about this issue in Google :(

The code I've written so far

function countLetter(str) {
    return str
        .replace(/\s/g, '')
        .split('')
        .reduce((a, b) => {
            return a === b ? b.replace(b, '') : b;
        });
}

window.onload = function () {
  console.log(countLetter('lorrem ipsssum dollorrrrum'));
}

2 Answers

With a regular expression, you can capture a character and then backreference that same character 1 or more times. Use a replacer function to replace the matched section with the character and the number of characters in the full match:

function countLetter(str) {
    return str
        .replace(/\s/g, '')
        .replace(/(\w)\1+/g, (match, char) => char + match.length);
}

console.log(countLetter('lorrem ipsssum dollorrrrum'));

With an alternation and a capture group, you might also use a single replacement.

Using a ternary operator, check if capture group 1 exists. If it does, return the single word character in group 1 (parameter g1) and append the length of the total match (parameter m).

If there is no group 1, then 1+ or more whitespace chars are matched due to the alternation |, which are replaced with an empty string.

(\w)\1+|\s+

Explanation

  • (\w)\1+ Capture a single word char in group 1 and repeat that same char 1 or more times which is in backreference \1
  • | Or
  • \s+ Match 1+ whitespace chars

const countLetter = s => s
  .replace(/(\w)\1+|\s+/g, (m, g1) => g1 ? g1 + m.length : '')

console.log(countLetter('lorrem ipsssum dollorrrrum'));

Related