How to replace the last appearance of a character?

Asked

Viewed 529 times

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);
    }

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, everything down 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 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 actually the most "traditional" way is the reply from @Anderson, which uses only string operations, extracting and concatenating substrings based on the position of the last comma (which can be obtained via String.lastIndexOf).

  • Perfect! For learning, how does this replace work? I didn’t understand these characters around the comma and 'e'.

  • I included a brief explanation, see if you can understand. Anything ask that I clarify.

  • What in that expression defines that is the last comma?

  • 1

    Is that the .* includes anything, including commas. So when you say .*, (anything followed by a comma), you will always fall in the last.

  • 1

    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.

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 the pos is the position in which the last , is found, he takes the string the front of the comma, put in the variable x, concatenates with ' and ' and then puts the rest of the string.

  • 1

    Like, with your answer I think all options are documented here! + 1

  • I was writing something a little more elaborate but in that same line of reasoning based on another solution of PHPJS. Also follow a Fiddle. And I imagine to be a more effective solution because it solves a string problem with string functions. Although it is possible to screw with a hammer, it is not right to do so (without disregarding the solutions based on arrays or Regexp).

5

You can do:

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

console.log(str);
  • Your example there in the checkbox question was excellent, deleted pq? Was going to comment, the system did not let... I took a snapshot before doing F5 :P

  • 1

    @brasofilo I was reversing the selection when I selected some check before clicking the button, I’ll fix it later, Valew

Browser other questions tagged

You are not signed in. Login or sign up in order to post.