jQuery查找并替换第二个 [英] jQuery find and replace second one

查看:420
本文介绍了jQuery查找并替换第二个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在div中查找和替换某些文本,但是我想查找并替换该文本的第二次出现.例如:您刚刚添加了一个项目,请删除该项目",因此我想找到第二个项目",并用我选择的任何文本替换.

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>

推荐答案

使用正则表达式即可

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

并称呼它

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

演示 http://jsfiddle.net/gaby/crhvA/

这篇关于jQuery查找并替换第二个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆