Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading