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

Time:12-29

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'

CodePudding user response:

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;
}

CodePudding user response:

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

CodePudding user response:

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

  • Related