是否有方法/函数可以获取规范/转换后的 URL,并尊重页面的任何 base.href 设置?
我可以通过(在 jQuery 中)使用 $("base").attr("href")
获取基本 URL,并且我可以使用字符串方法来解析要相对的 URL对此,但是
- $("base").attr("href") 没有主机、路径等属性(如 window.location 有)
- 手动将其组合在一起相当乏味
例如,给定一个 "http://example.com/foo/"
的 base.href 和一个相对 URL "/bar.js"
,结果应该是:“http://example.com/bar.js”
如果 base.href 不存在,则 URL 应相对于 window.location。 这应该处理不存在的base.href(在本例中使用位置作为基础)。
是否有可用的标准方法?
(我正在寻找这个,因为当使用像“/foo.js”这样的相对 URL 并且使用 BASE 标签时 jQuery.getScript 会失败(FF3.6 发出 OPTIONS 请求,而 nginx 无法处理这个请求)。当使用完整的 URL 时(base.href.host + “/foo.js”,它可以工作)。)
最佳答案
这能起到作用吗?
function resolveUrl(url){
if (!url) {
throw new Error("url is undefined or empty");
}
var reParent = /[\-\w]+\/\.\.\//, // matches a foo/../ expression
reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol
// replace all // except the one in proto with /
url = url.replace(reDoubleSlash, "$1/");
var base = (document.getElementsByTagName('BASE')[0] && document.getElementsByTagName('BASE')[0].href) || "";
// If the url is a valid url we do nothing
if (!url.match(/^(http||https):\/\//)) {
// If this is a relative path
var path = (url.substring(0, 1) === "/") ? base : location.pathname;
if (path.substring(path.length - 1) !== "/") {
path = path.substring(0, path.lastIndexOf("/") + 1);
}
if (!url.match(/^(http||https):\/\//)) {
url = location.protocol + "//" + location.host + path + url;
}
}
// reduce all 'xyz/../' to just ''
while (reParent.test(url)) {
url = url.replace(reParent, "");
}
return url;
}
它是根据我周围的一些代码修改的,因此尚未经过测试
关于javascript - 根据base.href或位置生成规范/真实URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2836174/