-2

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.

vish
  • 29
  • 4
  • 2
    @FarrukhChishti Obviously because this is a "code this for me" question with no attempt to solve it themselves. – Barmar Sep 09 '20 at 17:51
  • 1
    @FarrukhChishti But maybe they didn't notice the attempt in the text, since it's not highlighted as code. – Barmar Sep 09 '20 at 17:52
  • 1
    @FarrukhChishti Where does it say you have to comment? – epascarello Sep 09 '20 at 17:54
  • @Barmar: 1. He has provided a solution by specifying the regex he used. 2. Even if it was a "code this for me question" the downvoter must explicitly specify this. You can argue that the user should read the manual first but in this case, there is no reason to believe he did not read the manual. Also, its fair to give a little leverage to the new users, by atleast adding a short comment. Otherwise we will end up hounding every new user from this portal. – Farrukh Chishti Sep 09 '20 at 17:55
  • @FarrukhChishti I'm not excusing it, but in my experience 90% of downvotes don't come with a comment, so you're tilting at a big windmill. – Barmar Sep 09 '20 at 17:57
  • I didn't notice the regexp until I looked closer and then reformatted the question for the benefit of future readers. – Barmar Sep 09 '20 at 17:57
  • 1
    @FarrukhChishti [Users are not required to explain their downvotes.](https://meta.stackoverflow.com/questions/357436/why-isnt-providing-feedback-mandatory-on-downvotes-and-why-are-ideas-suggestin) – John Montgomery Sep 09 '20 at 17:58

2 Answers2

1

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,' + '));
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Make the regexp require another character after the ;, which you can copy to the result with a capture group.

s.replace(/;(.)/g, ' + $1')

At the end of the string there won't be a following character, so it won't match.

Barmar
  • 741,623
  • 53
  • 500
  • 612