How do I replace on the last occurrence of a character?

4

I have a loop that assembles strings in this format:

var Sabor[0] = "Mussarela, Calabresa, Cebola";
var Sabor[1] = "Mussarela, Presunto, Calabresa, Tomate, Ovos, Pimentão, Cebola";

But I would like to replace the last comma with an "e".

How do I do this?

At first it could be with replace, but there goes the loop code if someone 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);
    }
    
asked by anonymous 30.05.2014 / 01:47

3 answers

6

With Regex you can do it like this:

var str = "Mussarela, Presunto, Calabresa, Tomate, Ovos, Pimentão, Cebola";
str = str.replace(/(.*), (.*)/, '$1 e $2');
console.log(str); // "Mussarela, Presunto, Calabresa, Tomate, Ovos, Pimentão e Cebola"

The regular expression used separates the string into two parts, all to the last comma + space, and everything after that last space. In substitution, these two parts are referenced by $1 and $2 respectively.

Another way is by transforming into an array and reconstituting:

var str = "Mussarela, Presunto, Calabresa, Tomate, Ovos, Pimentão, Cebola";
var arr = str.split(', ');
var ultimo = arr.pop();
str = arr.join(', ') + ' e ' + ultimo;

And in fact the most "traditional" way is @ Anderson's answer , which uses only operations of strings, extracting and concatenating substrings based on the position of the last comma (which can be obtained via String.lastIndexOf ).

    
30.05.2014 / 01:59
6

It can be done this way:

var x = 'a,b,c';
var pos = x.lastIndexOf(',');
x = x.substring(0,pos)+' e '+x.substring(pos+1);

Where pos is the position where the last one is, it gets the string in front of the comma, places in the variable x , concatenates with ' e 'and then places the remainder of string .

    
30.05.2014 / 02:04
5

You can do:

var str = 'Mussarela, Calabresa, Cebola';
str = str.replace(/,([^,]*)$/,' e'+'$1');

console.log(str);
    
30.05.2014 / 02:04