【问题标题】:Count the instances of a string in a div, and remove all extra instances of that string with jQuery计算 div 中字符串的实例,并使用 jQuery 删除该字符串的所有额外实例
【发布时间】:2014-08-19 13:35:01
【问题描述】:

我要做的基本上是使用 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 来做到这一点?

【问题讨论】:

  • 你考虑过使用正则表达式吗?
  • 将字符串分成两部分:直到(包括第一次出现)的所有内容,以及之后的所有内容。然后使用.replace() 从第二部分中删除字符串。最后,将该结果连接到第一部分并将其存储回 DIV。

标签: jquery html string dom counter


【解决方案1】:

这是一种方法:

$('.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

【讨论】:

  • 看起来效果很好。但是如果要替换的字符串存储在 jQuery 变量中,你会怎么做呢?同样,我无法显示确切的文字,但这就是它的要点。
  • 应该像在上面的示例中删除变量代替 "a horse is a horse of course of course" 一样简单。您可能需要转义或连接它,但这只是一个小改动。
  • 出色的解决方案。谢谢!
猜你喜欢
  • 2018-08-22
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 2012-11-14
  • 2011-03-22
  • 1970-01-01
相关资源
最近更新 更多