Posted By

marcio on 01/25/10


Tagged

url javascript


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

johnloy


Parsing URLs with the DOM


 / Published in: JavaScript
 

URL: http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

Para parsear una url y acceder a sus parámetros, hash...

  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(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
  29. segments: a.pathname.replace(/^\//,'').split('/')
  30. };
  31. }
  32.  
  33.  
  34. //USAGE
  35. var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
  36.  
  37. myURL.file; // = 'index.html'
  38. myURL.hash; // = 'top'
  39. myURL.host; // = 'abc.com'
  40. myURL.query; // = '?id=255&m=hello'
  41. myURL.params; // = Object = { id: 255, m: hello }
  42. myURL.path; // = '/dir/index.html'
  43. myURL.segments; // = Array = ['dir', 'index.html']
  44. myURL.port; // = '8080'
  45. myURL.protocol; // = 'http'
  46. myURL.source; // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'

Report this snippet  

You need to login to post a comment.