在JavaScript中获取URL的href
参数值,通常指的是获取URL中?
后面的查询字符串(query string)中的特定参数值。以下是相关的基础概念、方法、优势及应用场景:
?
后面的部分,用于向服务器传递额外的参数。id=123
。可以使用以下几种方法来获取URL中的参数值:
URLSearchParams
// 假设当前URL为 https://example.com/page.html?id=123&name=John
const params = new URLSearchParams(window.location.search);
const id = params.get('id'); // "123"
const name = params.get('name'); // "John"
function getQueryParamByName(name) {
const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
const results = regex.exec(window.location.href);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
const id = getQueryParamByName('id'); // "123"
const name = getQueryParamByName('name'); // "John"
function getQueryParam(name) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(name);
}
const id = getQueryParam('id'); // "123"
const name = getQueryParam('name'); // "John"
URLSearchParams
接口提供了简洁的方法来处理查询字符串。URLSearchParams
,对于不支持的浏览器可以使用polyfill或正则表达式方法。decodeURIComponent
函数解码参数值。URLSearchParams
。通过以上方法,你可以轻松地在JavaScript中获取URL的href
参数值,并根据具体需求选择最适合的方法。
领取专属 10元无门槛券
手把手带您无忧上云