I have a few links which I would like to append with the word "SALE" based on a string in found the link, and I have successfully used the code below. However, I'd like to be able to have the code look at more than one string if possible.
Currently, the word "SALE" is appended to the links that contain the string "SHIRT". I'd also like it to be applied to all links that contain "JACKET" as well.
Is there a way of doing this as an array?
<div>
<div class="link"><a href="/products/WHITESHIRT">White Shirt</a></div>
<div class="link"><a href="/products/BLACKSHIRT">Black Shirt</a></div>
<div class="link"><a href="/products/GREENSHIRT">Green Shirt</a></div>
<div class="link"><a href="/products/WHITESHORTS">White Shorts</a></div>
<div class="link"><a href="/products/BLACKTROUSERS">Black Trousers</a></div>
<div class="link"><a href="/products/YELLOWJACKET">Yellow Jacket</a></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(".link a").each(function () {
var href=$(this).prop('href');
if (href.indexOf('SHIRT') > -1) {
$(this).append(" SALE");
}
});
</script>
Here you can use Array some
method
some
array.some(function(value, index, arr), this)
var keywords = ['SHIRT', 'JACKET'];
$(".link a").each(function () {
var href = $(this).prop('href');
if (keywords.some(function (v) { return href.indexOf(v) >= 0; })) {
$(this).append(" SALE");
}
console.log(keywords.some(function (v) { return href.includes(v) }))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="link"><a href="/products/WHITESHIRT">White Shirt</a></div>
<div class="link"><a href="/products/BLACKSHIRT">Black Shirt</a></div>
<div class="link"><a href="/products/GREENSHIRT">Green Shirt</a></div>
<div class="link"><a href="/products/WHITESHORTS">White Shorts</a></div>
<div class="link"><a href="/products/BLACKTROUSERS">Black Trousers</a></div>
<div class="link"><a href="/products/YELLOWJACKET">Yellow Jacket</a></div>
</div>