2

I was wondering how I would go about finding and replacing some text in a div, but i want to find and replace the second occurrence of that text. For example:"You just added a item, please remove this item" so I would like to find the second "item" and replace it with whatever text I choose.

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>
user229044
  • 232,980
  • 40
  • 330
  • 338
Lawrence
  • 837
  • 3
  • 12
  • 26

2 Answers2

2

"you currently have 1 item to compare" You want to turn item to items?

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

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

and

 $('.message').find('.type').text("items");
Pantelis
  • 6,086
  • 1
  • 18
  • 21
2

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 call it like

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

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

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317