Search code examples
javascriptpentahokettlerhino

Replace all semicolon with plus sign except last


i want to replace all semicolon (;) with plus (+) sign except the last semicolon.

ex -

i have something like this -

  • Apple;
  • Banana;
  • Apple;Banana;
  • Apple;Banana;Orange;
  • Apple;Banana;Orange;Mango;

i want to get result like this -

  • Apple;
  • Banana;
  • Apple + banana;
  • Apple + Banana + Orange;
  • Apple + Banana + Orange + Mango;

so far i tried

replace(/;/g, ' + ')

but this replace every semicolons.

the size of a line/word is dynamic i.e. changes from line to line.


Solution

  • With a look ahead

    console.log("A;".replace(/;(?=[^;]*;)/g,' + '));
    console.log("A;B;".replace(/;(?=[^;]*;)/g,' + '));
    console.log("A;B;C;".replace(/;(?=[^;]*;)/g,' + '));
    console.log("A;B;C;D;".replace(/;(?=[^;]*;)/g,' + '));