计算div中字符串的实例,并使用jQuery删除该字符串的所有额外实例

时间:2014-08-19 13:35:01

标签: jquery html string dom counter

我要做的是基本上使用jQuery在div中显示两次特定的字符串。由于我的工作性质,我不能分享确切的代码,但是我要说我有类似的东西:

<div class="sample">
    blah blah blah blah a horse is a horse of course of course blah blah blah blah
    blah a horse is a horse of course of course blah blah blah blah blah blah blah
    blah blah blah blah blah blah blah blah blah a horse is a horse of course of 
    course blah blah blah blah...
</div>

我不希望div显示“马当然是一匹马”,所以我想我想做的就是删除该短语的所有额外实例。我将如何使用jQuery进行此操作?

1 个答案:

答案 0 :(得分:0)

以这种方式:

$('.sample:contains("a horse is a horse of course of course")').text(function () {
    var match = 0;
    var newText = $(this).text().replace(/a horse is a horse of course of course/ig, function (str) {
        match++;
        return (match==1)?str:'';
    });
    return newText;
})

<强> jsFiddle example