4
I have a loop that mounts strings in this format:
var Sabor[0] = "Mussarela, Calabresa, Cebola";
var Sabor[1] = "Mussarela, Presunto, Calabresa, Tomate, Ovos, Pimentão, Cebola";
But I’d like to replace last comma for a " and".
How do I do that?
At first it could be with replace, but there goes the loop code if anyone has another idea.
function popularSabores(ClasseDiv, i) {
$(ClasseDiv.toString()).append("<p class='sabor_" + Id + "'>" + Sabor + "</p><p class='ingredientes_" + Id + "'></p>");
$.each(IngredientesArray, function (e, Ingredientes) {
var Ingrediente = Cardapio.Pizza[i].Ingredientes[e].Ingrediente;
if (e > 0) {
IngredientesString += ", ";
}
IngredientesString += Ingrediente;
});
$(".ingredientes_" + Id + "").append(IngredientesString);
}
Perfect! For learning, how does this replace work? I didn’t understand these characters around the comma and 'e'.
– Joao Paulo
I included a brief explanation, see if you can understand. Anything ask that I clarify.
– bfavaretto
What in that expression defines that is the last comma?
– Joao Paulo
Is that the
.*
includes anything, including commas. So when you say.*,
(anything followed by a comma), you will always fall in the last.– bfavaretto
If you look at @abfurlan’s suggestion, it works on the same principle, and its regular expression has become simpler: comma followed by anything except comma only occurs in the latter.
– bfavaretto