在 JavaScript 中获取路径参数

本文介绍了三种从URL中提取参数的方法:使用JavaScript的URLSearchParams对象,通过正则表达式匹配,以及自定义函数实现。分别展示了如何获取foo和bar参数的值。
摘要由CSDN通过智能技术生成

方法一:使用URLSearchParams对象

// 假设URL为 http://example.com/?foo=1&bar=2

const searchParams = new URLSearchParams(window.location.search);
const fooParam = searchParams.get('foo'); // 获取参数foo的值,结果为 "1"
const barParam = searchParams.get('bar'); // 获取参数bar的值,结果为 "2"

方法二:使用正则表达式

// 假设URL为http://example.com/?foo=1&bar=2

const urlParams = {};
const regExp = /[?&]+([^=&]+)=([^&]*)/g;
const matches = window.location.href.match(regExp);
matches.forEach(param => {
  const [_, key, value] = param.split('=');
  urlParams[key] = value;
});

const fooParam = urlParams['foo']; // 获取参数foo的值,结果为 "1"
const barParam = urlParams['bar']; // 获取参数bar的值,结果为 "2"

方法三:使用自定义函数

// 假设URL为 http://example.com/?foo=1&bar=2

function getUrlParam(name) {
  const regExp = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  const match = window.location.search.substr(1).match(regExp);
  if (match) {
    return decodeURI(match[2]);
  }
  return null;
}

const fooParam = getUrlParam('foo'); // 获取参数foo的值,结果为 "1"
const barParam = getUrlParam('bar'); // 获取参数bar的值,结果为 "2"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值