Reputation: 35
As the title suggests I'm trying to remove the last "," that appears when i return my function relative to a specific inputted name: For example I'm getting the following returned: "cat,bird,tiger, " when I'm trying to return "cat,bird,tiger " i have tried string = string.replace(/,\s*$/, ""); but this replaces all commas. here is my current code.
let string = "";
for(let i = 0; i < result.length; i++) {
console.log(result[i].animal)
string = string + result[i].animal + ",";
}
if(string != ""){
console.log(string);
}
else{
console.log("NOT FOUND");
}
Upvotes: 1
Views: 414
Reputation: 409
i use this code for everywhere i want have like this string
item,item,item,item,....,item
in first time i didn't add any comma and after then first add comma and then add item
if(string!=""){
string+=","
}
let string = "";
for(let i = 0; i < result.length; i++) {
if(string!=""){
string+=","
}
console.log(result[i].animal)
string = string + result[i].animal ;
}
if(string != ""){
console.log(string);
}
else{
console.log("NOT FOUND");
}
Upvotes: 0
Reputation: 370789
Map the array to the animal
properties, then join by a comma instead:
const string = result.map(({ animal }) => animal).join(',');
To tweak your original code, add a comma to the beginning of the concatenated string if string
is not empty:
let string = '';
for(let i = 0; i < result.length; i++) {
string += (string ? ',' : '') + result[i].animal;
}
Upvotes: 3