Home > front end >  How to detect if a link takes you to another page?
How to detect if a link takes you to another page?

Time:10-30

Let's say I have a function called linksToAnotherPage that receives an href. How can I check if the href takes you to another page or if it is a tel: , mailto:, #anchor-link, etc that does not take you to another page?

function linksToAnotherPage(href) {
 ....
}

linksToAnotherPage('tel:123-456-7890') -> // false
linksToAnotherPage('contact') -> // true

--

// does not link to another page

<a href="tel:123-456-7890">123-456-7890</a>
<a href="mailto:[email protected]">Send Email</a>
<a href="#start-now">Start Now</a>

// links to another page
<a href="contact">Send Email</a>

CodePudding user response:

You can just use a simple if statement for that, there are limited type of links which will go to another page:

  • links which starts with "/"
  • links which starts with "http://", "https://", or "wwww."

So, I think this function can help:

function linksToAnotherPage(href) {
   if (href.startsWith("/") || href.startsWith("http://" || href.startsWith("https://" || href.startsWith("www."){
      ....
   }
}

CodePudding user response:

function linksToAnotherPage(href) {
  let a = new URL(window.location.href);
  let b = new URL(href, window.location.href);
  return !['protocol', 'host', 'pathname', 'search']
    .every(i=>a[i]===b[i]);
}
  • Related