skip to Main Content

I’m learning JavaScript and practicing string manipulation using for loops. I’m trying to build a string that repeats a word multiple times, separated by commas, but without leaving an extra comma at the end.

Here’s an example:

  • Input: "hello", 3
  • Expected Output: "hello,hello,hello"

This is the code I’ve written so far:

function repeatWord(word, times) {
  let result = "";
  for (let i = 0; i < times; i++) {
    result += word + ",";
  }
  return result; // This adds an extra comma at the end. How can I fix this?
}

What I’ve Tried

  1. Using a for loop to add the word and a comma on each iteration. However, I haven’t figured out how to prevent the extra comma from being added after the final word.
  2. I’ve researched string manipulation techniques and found that methods like Array.join() could handle this easily:
Array(times).fill(word).join(",");

But I specifically want to use a for loop to improve my understanding of loops and conditionally appending characters.

  1. I’ve reviewed the MDN for loop documentation and beginner tutorials, but most focus on basic iteration or adding fixed patterns without addressing how to exclude trailing characters.

My goal is to modify my code to:

  • Repeat a word multiple times.
  • Add commas between each repetition.
  • Avoid adding a trailing comma after the last word.

This exercise is helping me learn how to use loops effectively for string building, so I’d appreciate an explanation focused on using for loops rather than alternative methods.

3

Answers


  1. You could add a condition and check result. If empty (falsy), take it otherwise take comma for adding.

    function repeatWord(word, times) {
        let result = "";
        for (let i = 0; i < times; i++) {
            result += (result && ',') + word;
        }
    
        return result;
    }
    console.log(repeatWord('hello', 1));
    console.log(repeatWord('hello', 2));
    console.log(repeatWord('hello', 3));
    Login or Signup to reply.
  2. Quick and easy fix, you can remove the last character in the string using the substring method:

    result.substring(0, result.length()-1);
    

    This return a new string containing the element from 0 to length()-1 meaning everything except the last character

    Login or Signup to reply.
  3. For this particular use, and to avoid evaluating an extra condition in every iteration, you could start with word before entering the loop, and have the loop make one iteration less. To support times being zero, you’ll need to add a condition:

    function repeatWord(word, times) {
      let result = times ? word : "";
      for (let i = 1; i < times; i++) {
        result += "," + word;
      }
      return result;
    }
    
    console.log(repeatWord('hello', 3));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search