Reputation: 167
I want to remove first duplicate month and year, I was able to remove the last duplicate words in text( ex. 30 December 2019 - 31 ). So my desired output example to be like this: 30 - 31 December 2019 This is what I have so far
$('.dates p').each(function(){
var string = $(this).text();
var newdatarange = string.split(' ').filter(function(allItems,i,a){
return i == a.indexOf(allItems);
}).join(' ');
$(this).text(newdatarange);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dates">
<p>10 December 2019 - 12 December 2019</p>
<p>14 December 2019 - 16 December 2019</p>
<p>20 December 2019 - 22 December 2019</p>
<p>30 December 2019 - 31 December 2019</p>
</div>
Upvotes: 2
Views: 94
Reputation: 3735
Just an alternative if you don't love regex
$('.dates p').each(function(){
var string = $(this).text();
var newdatarange = string.split('-');
if(newdatarange.length==2){
if($.trim(newdatarange[0]).substring(3)==$.trim(newdatarange[1]).substring(3))
string = $.trim(newdatarange[0]).substring(0, 2) + " - " + $.trim(newdatarange[1]).substring(0, 2) + " "+$.trim(newdatarange[0]).substring(3);
}
$(this).text(string);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dates">
<p>10 December 2019 - 12 December 2019</p>
<p>14 December 2019 - 16 December 2019</p>
<p>20 December 2019 - 22 December 2019</p>
<p>30 December 2019 - 31 December 2019</p>
</div>
Another option can be using filter method
$('.dates p').each(function(){
var string = $(this).text();
var newdatarange = string.split(' ').filter(function(allItems,i,a){
return a.indexOf(allItems, i+1)==-1;
}).join(' ');
$(this).text(newdatarange);
});
Upvotes: 1
Reputation: 386550
You could search for same parts and replace the string.
The regular expression looks for a capturing group which is repeated later.
$('.dates p').each(function() {
$(this).text($(this).text().replace(/(\D+\s+\d+)(?=.*\1)/, ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dates">
<p>10 December 2019 - 12 December 2019</p>
<p>14 December 2019 - 16 December 2019</p>
<p>20 December 2019 - 22 December 2019</p>
<p>30 December 2019 - 31 December 2019</p>
</div>
Upvotes: 3