Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 2.05 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. /*jslint regexp: true, sloppy: true, maxerr: 50, indent: 2 */
  2.  
  3. function parseURI(url) {
  4.   var m = String(url).match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
  5.   // authority = '//' + user + ':' + pass '@' + hostname + ':' port
  6.   return (m ? {
  7.     href     : m[0] || '',
  8.     protocol : m[1] || '',
  9.     authority: m[2] || '',
  10.     host     : m[3] || '',
  11.     hostname : m[4] || '',
  12.     port     : m[5] || '',
  13.     pathname : m[6] || '',
  14.     search   : m[7] || '',
  15.     hash     : m[8] || ''
  16.   } : null);
  17. }
  18.  
  19. function absolutizeURI(base, href) {// RFC 3986
  20.  
  21.   function removeDotSegments(input) {
  22.     var output = [];
  23.     input.replace(/^(\.\.?(\/|$))+/, '')
  24.          .replace(/\/(\.(\/|$))+/g, '/')
  25.          .replace(/\/\.\.$/, '/../')
  26.          .replace(/\/?[^\/]*/g, function (p) {
  27.       if (p === '/..') {
  28.         output.pop();
  29.       } else {
  30.         output.push(p);
  31.       }
  32.     });
  33.     return output.join('');
  34.   }
  35.  
  36.   href = parseURI(String(href || '').replace(/^\s+|\s+$/g, ''));
  37.   base = parseURI(String(base || '').replace(/^\s+|\s+$/g, ''));
  38.   if (href === null || base === null) {
  39.     return null;
  40.   }
  41.   var res = {};
  42.   if (href.protocol || href.authority) {
  43.     res.authority = href.authority;
  44.     res.pathname  = removeDotSegments(href.pathname);
  45.     res.search    = href.search;
  46.   } else {
  47.     if (!href.pathname) {
  48.       res.pathname = base.pathname;
  49.       res.search   = href.search || base.search;
  50.     } else {
  51.       if (href.pathname.charAt(0) === '/') {
  52.         res.pathname = removeDotSegments(href.pathname);
  53.       } else {
  54.         if (base.authority && !base.pathname) {
  55.           res.pathname = removeDotSegments('/' + href.pathname);
  56.         } else {
  57.           res.pathname = removeDotSegments(base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname);
  58.         }
  59.       }
  60.       res.search = href.search;
  61.     }
  62.     res.authority = base.authority;
  63.   }
  64.   res.protocol = href.protocol || base.protocol;
  65.   res.hash     = href.hash;
  66.   return res.protocol + res.authority + res.pathname + res.search + res.hash;
  67. }