简体   繁体   English

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

[英]How to get a URL by a relative path ? - Javascript

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

I want get result http://google.com/a/e.mp3 by baseURL and relativePath 我想通过baseURLrelativePath获得结果http://google.com/a/e.mp3

Is there an easy way to do it? 有一个简单的方法吗?

You can use this function: 你可以使用这个功能:

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'));

Here is the fiddle link: 这是小提琴链接:

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

Here it is user for something like same: Getting an absolute URL from a relative one. 这是用户的相似之处: 获取相对URL的绝对URL。 (IE6 issue) (IE6问题)

One way of doing it: 一种方法:

If you use Node.js you can use the path module to normalize your path. 如果使用Node.js,则可以使用路径模块规范化路径。 If you don't use Node.js you can still use this module in the browser with the help of browserify . 如果您不使用Node.js,您仍然可以在browserify的帮助下在浏览器中使用此模块。

Obviously you would need to get rid of d.html from the baseUrl and append the relativePath before you call path.normalize . 很明显,你需要摆脱d.htmlbaseUrl并追加relativePath打电话之前path.normalize

Take a look at this Gist . 看看这个要点 It worked quite well for me as it covers also special cases where simpler solutions will fail. 它对我来说效果很好,因为它还涵盖了更简单的解决方案将失败的特殊情况。

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;
}

You also need this helper function: 您还需要这个辅助函数:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM