CuriousDev
CuriousDev

Reputation: 1275

Specifying conditions while building an Array in jQuery

I am using the following to create an array of links that contains the word "micro"

var links = $('a[href*="micro"]');

This works great!

Now how do I specify that it should choose links that contain the word "micro" but not if "and" is present any where.

For eg:

https://xyz.com.com/2018/05/07/avoid-micro-mistakes/  //Allowed
https://xyz.com.com/2018/09/07/avoid-microproduction-and/  // Reject
https://xyz.com.com/2018/02/17/avoidand-production-micromistakes/  //Reject
https://xyz.com.com/2018/05/07/avoid-production-mismicrotakes/   //Allowed

I am unable to figure out how to provide the filter in my script.

Thanks in advance.

Upvotes: 0

Views: 30

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

You can use the :not psuedoselector to exclude hrefs that contain and, just like you're using your current selector to find hrefs that contain micro:

$('a[href*="micro"]:not([href*="and"])').css({ color: 'orange' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://xyz.com.com/2018/05/07/avoid-micro-mistakes/">some link</a>
<a href="https://xyz.com.com/2018/09/07/avoid-microproduction-and/">some link</a>
<a href="https://xyz.com.com/2018/02/17/avoidand-production-micromistakes/">some link</a>
<a href="https://xyz.com.com/2018/05/07/avoid-production-mismicrotakes/">some link</a>

These are vanilla CSS selectors, so it's just as easy to do this in vanilla JS, no need for a big library like jQuery if you don't want:

for (const a of document.querySelectorAll('a[href*="micro"]:not([href*="and"])')) {
  a.style.color = 'orange';
}
<a href="https://xyz.com.com/2018/05/07/avoid-micro-mistakes/">some link</a>
<a href="https://xyz.com.com/2018/09/07/avoid-microproduction-and/">some link</a>
<a href="https://xyz.com.com/2018/02/17/avoidand-production-micromistakes/">some link</a>
<a href="https://xyz.com.com/2018/05/07/avoid-production-mismicrotakes/">some link</a>

Upvotes: 3

Related Questions