expand a string in JavaScript to display letter and how many times that letter appears

782 Views Asked by At

Write a function that accepts a string where letters are grouped together and returns new string with each letter followed by a count of the number of times it appears. example : ('aeebbccd') should produce // 'a1e2b2c2d1'

function strExpand(str) {
  let results = ""

  for (let i = 0; i < str.length; i++) {
    let charAt = str.charAt(i)
    let count = 0

    results += charAt
    for (let j = 0; j < str.length; j++) {
      if (str.charAt(j) === charAt) {
        count++;

      }
    }

    results += count;
  }

  return results;
}

with the input 'aeebbccd' I am getting 'a1e2e2b2b2c2c2d1' instead of 'a1e2b2c2d1'

4

There are 4 best solutions below

0
I'mAUserNow On

This function is adding a number after each character, which is the number of times this character appears anywhere in the string. You could instead do it like this to get the result you want.

function strExpand(str) {
  let output = "";
  
  // Iterate through each character of the string, appending
  // to the output string each time
  for (let i = 0; i < str.length; i++) {
    let count = 1;

    // If the next character is the same, increase the count
    // and increment the index in the string
    while (str[i + 1] == str[i]) {
      count++;
      i++;
    }

    // Add the character and the count to the output string
    output += str[i] + count;
  }

  return output;
}
0
Yarin_007 On

For sake of completeness, how about a Regex?

const pattern = /(.)\1*/g; // put a char that exists in a capture group, then see if it repeats directly after
const s = 'aeebbccd';
var result = '';
for (match of s.match(pattern)) {
  let this_group = match;
  let this_len = match.length;
  result = result + this_group[0] + this_len; // get only the first letter from the group
}
console.log(result); // a1e2b2c2d1

0
Ali Amjid On

This would to the job. edit: hah i see im late :D, but still nice functional way to solve that.

/**
 * @param string to count
 * @return string $characterA$count. ex. abbccc -> a1b2c3
 */
function toCharacterCountString(str) {
    return Array.from(new Set(str).values())
        .map(char => {
            return `${char}${(str.match(new RegExp(char, "g")) || []).length}`;
        }).join('');
}


console.log(toCharacterCountString('abbccc')); // a1b2c3
console.log(toCharacterCountString('aeebbccd')); // a1e2b2c2d1

0
Unmitigated On

This can also be done with String#replace by matching all consecutive groups of the same character and passing a callback that returns the character concatenated to the length of the group.

const fn = str => str.replace(/(.)\1*/g, (g, c) => c + g.length);
console.log(fn('aeebbccd'));