uni-app中没有URL,手动实现一个可用的URL
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| class URL { constructor(url) { this.href = url this.origin = '' this.protocol = '' this.host = '' this.port = '' this.pathname = '' this.search = '' this.hash = '' this.params = {} this.getParams() } getParams () { const url = this.href if (!url || typeof url !== 'string') return const m = url.match(/(^https?:)\/\/((\w+\.)?(\w+\.?){2,})/) if (m) { if (m[0]) { this.origin = m[0] const pathRegExp = new RegExp(m[0] + '(:(\\d+))?([^\?#]*)?[\?#]*') const pathMatch = url.match(pathRegExp) if (pathMatch) { if (pathMatch[2]) this.port = pathMatch[2] if (pathMatch[3]) this.pathname = pathMatch[3] } } if (m[1]) this.protocol = m[1] if (m[2]) this.host = m[2] } const searchMatch = url.match(/\?([^#\?]*)?/g) const hashMatch = url.match(/#([^?\?]*)?/g)
if (hashMatch) { const arr = [] hashMatch.forEach((h,i) => { const hash = h.substring(1) hash.replace(/([^=&]+)?=([^=&]+)?/g, (_, a, b) => { this.params[a] = b }) arr.push(i === 0 ? h : h.replace('#', '&')) }) this.hash = arr.join('') }
if (searchMatch) { const arr = [] searchMatch.forEach((s, i) => { const search = s.substring(1) search.replace(/([^=&]+)?=([^=&]+)?/g, (_, a, b) => { this.params[a] = b }) arr.push(i === 0 ? s : s.replace('?', '&')) }) this.search = arr.join('') } } }
export default URL
|
使用
1 2 3
| import URL from 'url' const url = new URL('https://www.aaa.com:8989/bbb/ccc/ddd.html?e=1&f=2&g#h=3&i=4&j?k=5#l=6&e=4') console.log(url)
|
结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| { "href": "https://www.aaa.com:8989/bbb/ccc/ddd.html?e=1&f=2&g#h=3&i=4&j?k=5#l=6&e=4", "origin": "https://www.aaa.com", "protocol": "https:", "host": "www.aaa.com", "port": "8989", "pathname": "/bbb/ccc/ddd.html", "search": "?e=1&f=2&g&k=5", "hash": "#h=3&i=4&j&l=6&e=4", "params": { "h": "3", "i": "4", "l": "6", "e": "1", "f": "2", "k": "5" } }
|