JS中操作URL的相关方法

获取URL中的参数:

/*
** @param name{string}    // 参数名
*/
function getURLParam(name) {
    // 获取完整的查询参数字符串
    const queryString = window.location.search;

    // 创建URLSearchParams对象来解析查询参数
    const params = new URLSearchParams(queryString);

    // 使用get方法获取指定名称的参数值
    return params.get(name);
}

http://127.0.0.1:5500/URL.html?username=test&age=18

const username = getURLParam('username');
console.log(username); // "test"

const age = getURLParam('age');
console.log(age); // "18"

解析URL

const urlString = 'https://www.test.com:8080/path/url.html?username=test&age=18';
const url = new URL(urlString);

console.log(url.protocol);  // "https:"
console.log(url.host);      // "www.test.com:8080"
console.log(url.pathname);  // "/path/url.html"
console.log(url.search);    // "?username=test&age=18"
console.log(url.hostname);  // www.test.com
console.log(url.href);      // https://www.test.com:8080/path/url.html?username=test&age=18
console.log(url.origin);    // https://www.test.com:8080
console.log(url.port);      // 8080

// 解析查询参数
const searchParams = new URLSearchParams(url.search);
console.log(searchParams.get('username')); // "test"
console.log(searchParams.get('age')); // "18"

构建URL

在页面之间传参,不想手动把参数使用&符号一个一个拼起来时

  1. 使用URL构造函数构建URL

    const url = new URL('https://www.test.com');
    url.pathname = '/path';
    url.searchParams.set('username', 'test');
    url.searchParams.set('age', '18');
    console.log(url.toString()); // "https://www.test.com/path?username=test&age=18"
    
  2. 使用字符串拼接构建URL

    const baseUrl = 'https://www.test.com';
    const path = '/path';
    const params = new URLSearchParams({ username: 'test', age: '18' });
    const constructedUrl = `${baseUrl}${path}?${params.toString()}`;
    console.log(constructedUrl); // "https://www.test.com/path?username=test&age=18"
    
参数对应的值带=

如果动态传参时,参数对应的值含有=号,避免浏览器自动处理等号,使用encodeURIComponent方法

发送端:

const key = "BANXB1cAPFcEAGwFZgk=";
const encodedValue = encodeURIComponent(key);
const url = `edit.html?key=${encodedValue}`;
window.location.href = url;

接收端:

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const encodedValue = urlParams.get("key");
const decodedValue = decodeURIComponent(encodedValue);

因在项目中使用$.form.href("{:url('xy/test/group')}" + "?id=" + id + '&key='+key);这样跳转到页面2。其中key的值最后可能带有=号,跳转到页面2的时候,在页面2中获取到的key参数少了最后的=

如果大家使用window.location.href进行页面跳转时,在链接上传参,没有问题,可以忽略这个问题。

原创不易,转载请注明本文出处及原文链接。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值