parseUrl.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var staticLocation = require('./staticLocation')
  2. var unserialize = require('./unserialize')
  3. var helperGetLocatOrigin = require('./helperGetLocatOrigin')
  4. function parseURLQuery (uri) {
  5. return unserialize(uri.split('?')[1] || '')
  6. }
  7. function parseUrl (url) {
  8. var hashs, portText, searchs, parsed
  9. var href = '' + url
  10. if (href.indexOf('//') === 0) {
  11. href = (staticLocation ? staticLocation.protocol : '') + href
  12. } else if (href.indexOf('/') === 0) {
  13. href = helperGetLocatOrigin() + href
  14. }
  15. searchs = href.replace(/#.*/, '').match(/(\?.*)/)
  16. parsed = {
  17. href: href,
  18. hash: '',
  19. host: '',
  20. hostname: '',
  21. protocol: '',
  22. port: '',
  23. search: searchs && searchs[1] && searchs[1].length > 1 ? searchs[1] : ''
  24. }
  25. parsed.path = href.replace(/^([a-z0-9.+-]*:)\/\//, function (text, protocol) {
  26. parsed.protocol = protocol
  27. return ''
  28. }).replace(/^([a-z0-9.+-]*)(:\d+)?\/?/, function (text, hostname, port) {
  29. portText = port || ''
  30. parsed.port = portText.replace(':', '')
  31. parsed.hostname = hostname
  32. parsed.host = hostname + portText
  33. return '/'
  34. }).replace(/(#.*)/, function (text, hash) {
  35. parsed.hash = hash.length > 1 ? hash : ''
  36. return ''
  37. })
  38. hashs = parsed.hash.match(/#((.*)\?|(.*))/)
  39. parsed.pathname = parsed.path.replace(/(\?|#.*).*/, '')
  40. parsed.origin = parsed.protocol + '//' + parsed.host
  41. parsed.hashKey = hashs ? (hashs[2] || hashs[1] || '') : ''
  42. parsed.hashQuery = parseURLQuery(parsed.hash)
  43. parsed.searchQuery = parseURLQuery(parsed.search)
  44. return parsed
  45. }
  46. module.exports = parseUrl