假设我在不同域(mydomain.com)的页面上,并且相对URL仅存在于代码中(不在DOM中)
如何在javascript中完全合并两个任意网址?
var a = 'http://example.com/some/path/';
var b = '../other/path/';
var c = magicUrlCombine(a,b);
assert(c == 'http://example.com/some/other/path/');
它也适用于
var a = 'http://example.com/some/path/';
var b = 'http://pink-unicorns.com/some/other/path/';
var c = magicUrlCombine(a,b);
assert(c == 'http://pink-unicorns.com/some/other/path/');
修改
我正在寻找一个完全通用的功能,用于将绝对网址与任意网址相结合。与浏览器用于解析链接的逻辑相同,但用于不在页面HTML中和/或不相对于当前location.href的URL。
var a = 'http://example.com/a/b/c/';
var b = '../d/e/';
assert(c == 'http://example.com/a/b/d/e/')
OR
var b = '/f/g/';
assert(c == 'http://example.com/f/g/')
OR
var b = 'http://jquery.com/h/i/';
assert(c == 'http://jquery.com/h/i/')
编辑2:
node.js有一个url module具有正确的功能,但我还没有找到一种在客户端重用它的好方法。 (how to use node.js module system on the clientside)
我设法破解了我的工作方式,但这并不是一个真正的解决方案,我觉得放入生产网站很舒服。 Hackety hack
答案 0 :(得分:2)
JQuery Mobile有它
$.mobile.path.makeUrlAbsolute(relPath, absPath)
console.log($.mobile.path.makeUrlAbsolute('../d/e/', 'http://example.com/a/b/c/'));
console.log($.mobile.path.makeUrlAbsolute('/f/g/', 'http://example.com/a/b/c/'));
console.log($.mobile.path.makeUrlAbsolute('http://jquery.com/h/i/', 'http://example.com/a/b/c/'));
都给出了预期的结果
答案 1 :(得分:2)
我在服务器端使用NodeJS
var url = require('url');
url.resolve(from, to);
在你的情况下:
var a = 'http://example.com/some/path/';
var b = '../other/path/';
var c = url.resolve(a, b);
assert(c == 'http://example.com/some/other/path/');
var a = 'http://example.com/some/path/';
var b = 'http://pink-unicorns.com/some/other/path/';
var c = url.resolve(a, b);
assert(c == 'http://pink-unicorns.com/some/other/path/');
答案 2 :(得分:1)
无法抗拒解决方案
var magicUrlCombine = function(a,b){
return (a + b).replace(/[\w\-\.]+\/..\/|\:\/\/[\w\-\.\/]+http/g,'');
}
适用于测试用例和两者的组合
答案 3 :(得分:1)
这是一种可能但未经测试的解决方案:
function magicCombine(a,b){
if(b.indexOf('://') != -1) return b;
var backs = 0;
var lastIndex = b.indexOf('../');
while(lastIndex != -1){
backs++;
lastIndex = b.indexOf('../', lastIndex+3);
}
var URL = a.split('/');
//Remove last part of URL array, which is always either the file name or [BLANK]
URL.splice(URL.length-1, 1)
if(b.substr(0,1) == '/')
b = b.substr(1);
var toAdd = b.split('/');
for(var i = 0, c = toAdd.length-backs; i < c; ++i){
if(i < backs)
URL[URL.length - (backs-i)] = toAdd[backs+i];
else
URL.push(toAdd[backs+i]);
}
return URL.join('/');
}
应该照顾这两种情况......
答案 4 :(得分:1)
我以为我理解了这个问题,但我的小提琴返回两个错误。这些例子并不明显
http://jsfiddle.net/mplungjan/z5SUn/
function magicUrlCombine(a,b) {
var linkA = document.createElement('a');
linkA.href = a;
var linkB = document.createElement('a');
linkB.href = b;
return linkB.href.replace(linkB.host,linkA.host)
}