我正在尝试使用以下命令将 URL 字符串转换为 URL 对象:
var newUrl = new URL("http://www.testsite.com?name=abc&class=123");
它适用于 Chrome 和 Firefox,但不适用于 IE11。是否有已知的解决方法?
谢谢。
最佳答案
不,URL 对象在 IE 中不可用 https://developer.mozilla.org/en-US/docs/Web/API/URL
但是,您可以使用一些小型库来伪造它 http://blog.stevenlevithan.com/archives/parseuri
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
// http://blog.stevenlevithan.com/archives/parseuri
function parseUri (str) {
var o = parseUri.options,
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;
while (i--) uri[o.key[i]] = m[i] || "";
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) uri[o.q.name][$1] = $2;
});
return uri;
};
parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};
使用
parseUri.options.strictMode = true;
关于url - IE11 - 对象不支持此操作 - URL 对象 - 解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48525252/