在JavaScript中获取URI(Uniform Resource Identifier,统一资源标识符)通常指的是获取当前页面的URL或者URL中的特定部分。以下是一些基础概念和方法:
你可以使用window.location.href
来获取当前页面的完整URL。
var currentURL = window.location.href;
console.log(currentURL);
window.location
对象提供了多个属性来获取URL的不同部分:
window.location.protocol
:获取URL的协议部分(包括冒号),例如"http:"或"https:"。window.location.hostname
:获取URL的主机名,例如"www.example.com"。window.location.port
:获取URL的端口号,如果没有指定端口,则返回空字符串。window.location.pathname
:获取URL的路径名,例如"/path/to/file"。window.location.search
:获取URL的查询字符串部分,包括问号(?),例如"?id=123"。window.location.hash
:获取URL的片段标识符,包括井号(#),例如"#section1"。如果你需要获取URL中的特定查询参数,可以使用以下方法:
function getQueryParamByName(name, url = window.location.href) {
let queryStr = url.split('?')[1];
if (!queryStr) return null;
let paramsArray = queryStr.split('&');
for (let i = 0; i < paramsArray.length; i++) {
let param = paramsArray[i].split('=');
if (decodeURIComponent(param[0]) === name) {
return decodeURIComponent(param[1] || '');
}
}
return null;
}
let id = getQueryParamByName('id');
console.log(id); // 输出查询参数id的值
%20
。使用decodeURIComponent
函数可以将这些编码的字符解码回原始字符。以上是关于在JavaScript中获取URI的基础知识和方法。如果你有更具体的问题或遇到特定的问题,请提供详细信息以便进一步解答。
领取专属 10元无门槛券
手把手带您无忧上云