JSFiddle - React, Tailwind, and code Playground

by Gabriele Petrioli

HTML

<div id="alertMessage">
    <div class="message">
        <span>You just added an item to compare, you currently have <span class="count">1</span> item to compare</span>
    </div>
</div>

JavaScript

function replaceMatch(originalString, searchFor , replaceWith, matchNumber)
{
  var match = 0;
  return originalString.replace(searchFor, function(found){
                     match++;
                     return (match===matchNumber)?replaceWith:found;
                   },'g');
}

$(function(){
    var msg = $('.message');
    msg.html( replaceMatch( msg.html(), 'item', 'items', 2) );
});