JQuery find and replace the second

I was wondering how I am going to find and replace some text in a div, but I want to find and replace the second occurrence of this text. For example: “You just added an element, please delete this element”, so I would like to find the second “element” and replace it with any text that I select.

JS:

var compareCount = $('.compareWidget').find('.compareItem').length;

if (compareCount >= 2) {
    $('.message').find('.count').text(compareCount);
    $('message').html().replace('item', 'items');
}

$('.message').slideDown("Fast");

setTimeout(function () {
    $('.message').slideUp("Fast");
}, 5000);

HTML:

<div id="alertMessage">
    <div class="message">
        <span>You just added a item to compare, you currently have <span class="count">1</span> item to compare</span>
    </div>
</div>
+3
source share
2 answers

"you currently have 1 item to compare" Do you want to swap an item for items?

You can do this with regular expressions, or you can wrap it in an element and grab it.

<span class="count">1</span> <span class="type">item</span> to compare</span>

and

 $('.message').find('.type').text("items");
+2
source

Using regular expressions, you can

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

and name it like

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

demo http://jsfiddle.net/gaby/crhvA/

+2
source

All Articles