What\'s the fastest method to detect if foo=\'http://john.doe\'
is an external url (in comparsion to window.location.href
)?
The main problem, is how to parse an URL, and get a host name our of it. It can be done with following way:
var _getHostname = function(url) {
var parser = document.createElement('a');
parser.href = url;
return parser.hostname;
}
var isExternal = (_getHostname(window.location.href) !== _getHostname('http://john.doe'));
Or you can use is-url-external module.
var isExternal = require('is-url-external');
isExternal('http://john.doe'); // true | false
You can simply use use npm package is-internal-link
Installation
npm install --save is-internal-link
Usage
import { isInternalLink } from "is-internal-link"
isInternalLink('https://www.google.com') // false
isInternalLink('/page1') // true
I also usually this with react like this
import React from 'react'
import { Link as ReactRouterLink} from 'react-router-dom'
import { isInternalLink } from 'is-internal-link'
const Link = ({ children, to, activeClassName, ...other }) => {
if (isInternalLink(to)) {
return (
<ReactRouterLink to={to} activeClassName={activeClassName} {...other}>
{children}
</ReactRouterLink>
)
}
return (
<a href={to} target="_blank" {...other}>
{children}
</a>
)
}
export default Link
Disclaimer: I am the author of this lib
Shouldn't
function is_external( url ) {
return url.match( /[a-zA-Z0-9]*:\/\/[^\s]*/g ) != null;
}
do the trick? Doesn't work for absolute (internal) urls.