Posted By

mifly on 02/28/09


Tagged

parseURL


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

endorfin
goliatone


parseURL


 / Published in: JavaScript
 

  1. // This function creates a new anchor element and uses location
  2. // properties (inherent) to get the desired URL data. Some String
  3. // operations are used (to normalize results across browsers).
  4.  
  5. function parseURL(url) {
  6. var a = document.createElement('a');
  7. a.href = url;
  8. return {
  9. source: url,
  10. protocol: a.protocol.replace(':',''),
  11. host: a.hostname,
  12. port: a.port,
  13. query: a.search,
  14. params: (function(){
  15. var ret = {},
  16. seg = a.search.replace(/^\?/,'').split('&'),
  17. len = seg.length, i = 0, s;
  18. for (;i<len;i++) {
  19. if (!seg[i]) { continue; }
  20. s = seg[i].split('=');
  21. ret[s[0]] = s[1];
  22. }
  23. return ret;
  24. })(),
  25. file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
  26. hash: a.hash.replace('#',''),
  27. path: a.pathname.replace(/^([^\/])/,'/$1'),
  28. relative: (a.href.match(/tp:\/\/[^\/]+(.+)/) || [,''])[1],
  29. segments: a.pathname.replace(/^\//,'').split('/')
  30. };
  31. }

Report this snippet  

You need to login to post a comment.