Fastest way to detect external URLs

前端 未结 9 1431
孤街浪徒
孤街浪徒 2020-12-02 14:23

What\'s the fastest method to detect if foo=\'http://john.doe\' is an external url (in comparsion to window.location.href)?

相关标签:
9条回答
  • 2020-12-02 15:23

    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 
    
    0 讨论(0)
  • 2020-12-02 15:24

    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

    0 讨论(0)
  • 2020-12-02 15:29

    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.

    0 讨论(0)
提交回复
热议问题