如何通过相对路径获取URL? - Javascript

时间:2014-04-19 05:51:25

标签: javascript

var baseURL = "http://google.com/a/b/c/d.html";
var relativePath = "../../e.mp3";

我希望http://google.com/a/e.mp3baseURL

获取结果relativePath

有一种简单的方法吗?

3 个答案:

答案 0 :(得分:4)

您可以使用此功能:

function resolve(url, base_url) {


  var doc      = document
    , old_base = doc.getElementsByTagName('base')[0]
    , old_href = old_base && old_base.href
    , doc_head = doc.head || doc.getElementsByTagName('head')[0]
    , our_base = old_base || doc_head.appendChild(doc.createElement('base'))
    , resolver = doc.createElement('a')
    , resolved_url
    ;
  our_base.href = base_url;
  resolver.href = url;
  resolved_url  = resolver.href; // browser magic at work here

  if (old_base) old_base.href = old_href;
  else doc_head.removeChild(our_base);
  return resolved_url;
}
alert(resolve('../../e.mp3', 'http://google.com/a/b/c/d.html'));

这是小提琴链接:

http://jsfiddle.net/ecmanaut/RHdnZ/

用户可以使用相同的内容:Getting an absolute URL from a relative one. (IE6 issue)

答案 1 :(得分:0)

一种方法:

如果您使用Node.js,您可以使用path模块来规范化您的路径。如果您不使用Node.js,您仍然可以在browserify的帮助下在浏览器中使用此模块。

显然,您需要从d.html中删除baseUrl并在致电relativePath之前附加path.normalize

答案 2 :(得分:-1)

看看这个Gist。它对我来说效果很好,因为它还涵盖了更简单的解决方案失败的特殊情况。

function absolutizeURI(base, href) {// RFC 3986

  function removeDotSegments(input) {
    var output = [];
    input.replace(/^(\.\.?(\/|$))+/, '')
         .replace(/\/(\.(\/|$))+/g, '/')
         .replace(/\/\.\.$/, '/../')
         .replace(/\/?[^\/]*/g, function (p) {
      if (p === '/..') {
        output.pop();
      } else {
        output.push(p);
      }
    });
    return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
  }

  href = parseURI(href || '');
  base = parseURI(base || '');

  return !href || !base ? null : (href.protocol || base.protocol) +
         (href.protocol || href.authority ? href.authority : base.authority) +
         removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
         (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
         href.hash;
}

您还需要这个辅助功能:

function parseURI(url) {
  var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
  // authority = '//' + user + ':' + pass '@' + hostname + ':' port
  return (m ? {
    href     : m[0] || '',
    protocol : m[1] || '',
    authority: m[2] || '',
    host     : m[3] || '',
    hostname : m[4] || '',
    port     : m[5] || '',
    pathname : m[6] || '',
    search   : m[7] || '',
    hash     : m[8] || ''
  } : null);
}