Remove duplicated text using jquery
-
13-06-2021 - |
Question
say I have the following
<h3>This is my heading</h3>
<p>This is my headingAnd this is part of a paragraph</p>
I want to end up with the following
<h3>This is my heading</h3>
<p>And this is part of a paragraph...</p>
I found this code
$(function() {
var seen = {};
$('p, h3').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
});
but because there are two words joined in the paragraph it won't work. The data is being pulled dynamically from a rss feed.
Thanks in advance
Solution
If you DOM structure remain as you stated above then following will work for you:
$('p').text(function(index, oldText) {
return oldText.replace($(this).prev('h1').text(), '');
});
According to your comment
<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(), '');
});
OTHER TIPS
var header = $('h1').text();
var body = $('p').text();
if (body.indexOf(header) >= 0) {
$('p').text(body.replace(header, ''));
}
Demo
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow