怎么用js获取url
原创怎样使用JavaScript获取URL
在JavaScript中,你可以使用window.location
对象来获取当前页面的URL。这个对象提供了许多有用的属性,包括href
、protocol
、host
、hostname
、port
、pathname
、search
和hash
。
以下是一个单纯的示例,展示了怎样使用JavaScript获取当前页面的完整URL:
// 获取当前页面的完整URL
var currentURL = window.location.href;
console.log(currentURL);
如果你只对URL的某一部分感兴趣,例如查询字符串,你可以使用search
属性:
// 获取URL中的查询字符串
var queryString = window.location.search;
console.log(queryString);
如果你想从查询字符串中提取特定的参数,你可以使用以下方法:
// 从查询字符串中提取参数
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
// 使用函数获取查询参数
var myParam = getParameterByName('myParam');
console.log(myParam);
这个getParameterByName
函数可以从URL的查询字符串中提取指定的参数,并返回其值。如果没有找到该参数,函数将返回null
。