jollen / blog

Jollen's Blog
http://www.jollen.org/blog
66 stars 4 forks source link

Best Practice for Checking Web Protocols URI #17

Open jollen opened 8 years ago

jollen commented 8 years ago

一個實作筆記:如何檢查 URI 的格式是否正確?例如,以下是幾個正確的 URI:

這裡有二個實作。

方法 1

    if (!/^(https?|wss?):\/\//.test(uri)) {
      debug('protocol-less url %s', uri);
      if ('undefined' != typeof loc) {
        uri = loc.protocol + '//' + uri;
      } else {
        uri = 'https://' + uri;
      }
    }

方法 2

  // make sure we treat `localhost:80` and `localhost` equally
  if (!obj.port) {
    if (/^(http|ws)$/.test(obj.protocol)) {
      obj.port = '80';
    }
    else if (/^(http|ws)s$/.test(obj.protocol)) {
      obj.port = '443';
    }
  }