Reputation:
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>
--
UPDATE: here is my current solution based on the answers received
function isInteractiveHref (href) {
return (
href.startsWith("mailto:") || href.startsWith("tel:") ||
href.startsWith("#")
)
}
isInteractiveHref(props.href) ? (
<Link href={props.href}>
<a>Does not link to another page</a>
</Link>
) : <Link href={'/' + props.href}>
<a> Links to another page</a>
</Link>
Upvotes: 2
Views: 75
Reputation: 8107
function linksToAnotherPage(href) {
if(['tel','mailto'].some(i=>href.startsWith(`${i}:`))) return false;
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]);
}
You can find a list of URL prefixes you may want to additionally match here: https://en.wikipedia.org/wiki/List_of_URI_schemes
Upvotes: 0
Reputation: 709
You can just use a simple if statement for that, there are limited type of links which will go to another page:
So, I think this function can help:
function linksToAnotherPage(href) {
if (href.startsWith("/") || href.startsWith("http://" || href.startsWith("https://" || href.startsWith("www."){
....
}
}
Upvotes: 1