使用jquery删除重复的文本

时间:2012-06-12 06:22:34

标签: jquery

说我有以下

 <h3>This is my heading</h3>
 <p>This is my headingAnd this is part of a paragraph</p>

我想最终得到以下内容

 <h3>This is my heading</h3>
 <p>And this is part of a paragraph...</p>

我找到了这段代码

   $(function() {
   var seen = {};
    $('p, h3').each(function() {
    var txt = $(this).text();
     if (seen[txt])
     $(this).remove();
   else
     seen[txt] = true;
  });
});

但由于段落中加入了两个单词,因此无效。数据是从rss Feed中动态提取的。

提前致谢

2 个答案:

答案 0 :(得分:3)

如果DOM结构保持如上所述,则以下内容适用于您:

$('p').text(function(index, oldText) {
  return oldText.replace($(this).prev('h1').text(), '');
});

<强> DEMO

根据您的评论

<div id="youtube">
    <section>
        <h3>Launch of the Active Living impact checklist</h3>
        <p>Launch of the Active Living impact checklistFrom test</p>
        <a target="_blank" href="#"> watch video</a> <br>
    </section>
    <section>
        <h3>Enterprise Computing Conference</h3>
        <p>Enterprise Computing ConferenceWorld leaders in enterprise computing attended a two</p>
        <a target="_blank" href="#"> watch video</a> <br>
    </section>
</div>

$('p').text(function(index, oldText) {
  return oldText.replace($(this).prev('h3').text(), '');
});

<强> DEMO

答案 1 :(得分:0)

var header = ​$('h1').​​​​text();
var body = $('p').text();

if (body.indexOf(header) >= 0) {
    $('p').text(body.replace(header, ''));
}

Demo