Posted By

marcio on 02/21/09


Tagged

url javascript parse


Versions (?)

Who likes this?

6 people have marked this snippet as a favorite

LeeRJohnson
jamesming
sulfurito
polarbear
jschilling
seanpowell


Parsing URLs with the DOM!


 / Published in: JavaScript
 

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

funcion para parsear la url y obtener todos sus datos

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

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Sephr on February 24, 2009

location.host !== location.hostname (location.host includes any non-normal ports) You should replace line 11 with this:

host: a.host,
hostname: a.hostname,

You need to login to post a comment.