3

Edit:

Annoyed that this was marked as a duplicate when the solution is very clearly different...

To give some more information on why I am asking this, I am building a web game. In the game, there are items that you can build which costs certain ingredients.

What the function does is that it loops through all the requirements of the item and builds out a string that looks something like this:

let costStr = `
  <span class='enough'>coal: 5, </span>
  <span class='not-enough'>iron: 5, </span>
  <span class='enough'>copper: 10, </span>
`

And then I append the string into an element on the page: costStr.innerHTML = costStr

The problem with this was because unlike other stackoverflow questions about removing commas, I didnt want to remove everything after the last comma because that would remove the span tag as well.


Example input string: <span>test, </span><span>test, </span><span>test, </span>

What I want: <span>test, </span><span>test, </span><span>test </span>

Tried some solutions that I found online but those don't take into account html tags that might be at the end of the string.

Is this possible with regex? Just replacing the last comma within a string with nothing?

Thanks!

Syn
  • 938
  • 1
  • 10
  • 21
  • 4
    I think you'd be done faster and more happy with [String.prototype.lastIndexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf), but you can use a lookahead for "some character but no comma", e.g. `/,(?!.*,)(?=[^,])/` – ASDFGerte Dec 21 '19 at 21:02
  • @ASDFGerte Awesome. Didn't know about lastIndexOf. Ill use that. You regex also works as well! – Syn Dec 21 '19 at 21:06
  • What probably also works is `/,(?=[^,]+$)/`, as long as no multiline flag `m` is going to be used – ASDFGerte Dec 21 '19 at 21:20
  • 2
    How did the string get made? I suggest that when making the string, don't put the comma in the last one. – Andrew Morton Dec 21 '19 at 21:57
  • This improves @ASDFGerte suggestion a little `,(?![\s\S]*,)` –  Dec 21 '19 at 21:59
  • Usually when people ask this question it's because they're concatenating strings using a for loop. Rather you should use the array.join(separator) function to join strings together. – quano Dec 21 '19 at 22:09
  • I am using a loop to concatenate a string – Syn Dec 23 '19 at 16:29

0 Answers0