Trim Last Character(s) from a String in Javascript

Today, I had a need to join comma separated strings in Javascript which turned out to be very easy. I wrote something similar to this

for(var i=0; i < length; i++){
string=string+labels[i]+”,”
}

where string was defined as a var and labels as array.

The difficult part was to remove the last comma. After googling for fifteen minuted, I decided to read the documentation on Strings and found the substring function which turned out to be perfect solution.

string = string.substring(0, string.length-1)

Leave a Reply