/** * 解析一個url並生成window.location對象中包含的域 * location: * { * href: '包含完整的url', * origin: '包含協議到pathname以前的內容', * protocol: 'url使用的協議,包含末尾的:', * username: '用戶名', // 暫時不支持 * password: '密碼', // 暫時不支持 * host: '完整主機名,包含:和端口', * hostname: '主機名,不包含端口' * port: '端口號', * pathname: '服務器上訪問資源的路徑/開頭', * search: 'query string,?開頭', * hash: '#開頭的fragment identifier' * } * * @param {string} url 須要解析的url * @return {Object} 包含url信息的對象 */ function parseUrl(url) { var result = {}; var keys = ['href', 'origin', 'protocol', 'host', 'hostname', 'port', 'pathname', 'search', 'hash']; var i, len; var regexp = /(([^:]+:)\/\/(([^:\/\?#]+)(:\d+)?))(\/[^?#]*)?(\?[^#]*)?(#.*)?/; var match = regexp.exec(url); if (match) { for (i = keys.length - 1; i >= 0; --i) { result[keys[i]] = match[i] ? match[i] : ''; } } return result; }
參考:https://github.com/sunlianguang/FE-interview#解析一個完整的url返回object包含域與windowlocation相同