Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialLuke Lee
7,577 PointsRemove last comma from for loop
I am studying javascript for loop, below is the code I am using, the output is like: a,b,c,d, my questions is how to remove the last comma from the output? or replace it with a .
document.getElementById("result").innerHTML += str;
3 Answers
Armand Ramirez
4,016 PointsLuke! You're in luck, my brother...
I recent wrote a Pig Latin translator: http://eightbitadder.com/pig/ and one of my functions will work for your needs:
function removeComma(word){
var stringArray = []; // the word is broken into an array
for(j=0;j<word.length;j++){
letter = word.charAt(j); // the letter in the array to be tested
if(letter == ","){ // if the letter is a "," replace it with a "."
stringArray.push(".")
} else { // otherwise, just push the letter to the array
stringArray.push(letter);
}
}
noCommaWord = stringArray.join(""); // join the new array (without commas) together
return noCommaWord; //retur the new word
}
var str = "string,"
console.log(removeComma(str));
What this does is the following: 1) breaks your inputted string into an array 2) loops over each index of the array (each letter in the word) and checks if there's a comma 3) if there's a comma, it replaces it with a period.
Copy the code into chrome console and you'll see that it works. If you see how this function works, you can modify it to look for other characters as well ... just add additional if else statements to screen for other letters.
There's also some additional code you can insert to drop off commas (or other characters) if they occur before the end of the string, but I'll leave that up to you!
Have fun,
-Armand
Darren Hoyne
2,384 PointsI'll throw in my two pence, I have not done JavaScript before but I do Java and their quite similar.
Sounds like you need to do a check for something like 'isLast' or isLastELement' something of this type...And on that to change the format of what you print out by removing the comma.
So if you know how long the loop is, in Java it would be like
i=0;
For(x>alphabet[])
{
if( i == lastElement)
{
print ( alphabet[i] );
}
else{
print( alphabet[i]) + ", " );
}
}
I understand this isnt Javascript and I am sorry, but this would more or less be the logic behind what you are trying to do.
Darren Hoyne
2,384 PointsIt wont format for me right :( Sorry I hope its some bit legible