Search code examples
javascriptjqueryanchorhref

Replace HREF with hash if URL contains specific word


In my home page I have links in a pattern. The URLs have portfolio-item in the href.

Ex:

  1. www.mysite.com/portfolio-item/whatEver1
  2. www.mysite.com/portfolio-item/whatEver2
  3. www.mysite.com/portfolio-item/whatEver3

For now I have to find if a URL has the word portfolio-itemor not. If portfolio-item is found then I have to relace the href to #

What I mean is:

If the anchor tag is <a href="www.mysite.com/portfolio-item/whatEver">What Ever</a>what ever I have to change it to <a href="#">what ever</a>

Because the above HREF has the word portfolio-item.

How can I check the all the anchor tags which are in page and check for the word portfolio-item and if it is found then replace the href value to # using jQuery?


Solution

  • Use attribute contains selector

    $('a[href*="portfolio-item"]').attr('href', '#');
    

    The selector a[href*="portfolio-item"] will select all the <a> elements whose href attribute value contains the string portfolio-item anywhere.