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
- 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.
- 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.
- 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
You could add a condition and check
result
. If empty (falsy), take it otherwise take comma for adding.Quick and easy fix, you can remove the last character in the string using the substring method:
This return a new string containing the element from
0
tolength()-1
meaning everything except the last characterFor 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 supporttimes
being zero, you’ll need to add a condition: