返回
js如何获取url参数,向url字符串追加参数,location.href详解
前端
2024-02-14 06:35:44
背景
很多时候,我们需要获取另外一个页面url传过来的参数。我们可以手动传入url或者使用默认的location.href(search)。由于uri很多时候特殊字符会有歧义,一般的url需要经过encodeURIComponent编码,获取时需要decodeURIComponent解码。
获取URL参数
获取URL参数有以下几种方式:
- 使用location.href
const url = location.href;
const params = new URLSearchParams(url.search);
const paramValue = params.get('paramName');
- 使用正则表达式
const url = 'https://example.com/page?paramName=paramValue';
const regex = /paramName=([^&]+)/;
const matches = url.match(regex);
const paramValue = matches[1];
- 使用库
有很多库可以帮助我们获取URL参数,例如query-string和qs。
const qs = require('qs');
const url = 'https://example.com/page?paramName=paramValue';
const params = qs.parse(url);
const paramValue = params['paramName'];
向URL字符串追加参数
向URL字符串追加参数有以下几种方式:
- 使用location.href
location.href += '?paramName=paramValue';
- 使用URLSearchParams
const url = new URL('https://example.com/page');
const params = new URLSearchParams(url.search);
params.append('paramName', 'paramValue');
url.search = params.toString();
- 使用库
有很多库可以帮助我们向URL字符串追加参数,例如query-string和qs。
const qs = require('qs');
const url = 'https://example.com/page';
const params = qs.parse(url);
params['paramName'] = 'paramValue';
const newUrl = qs.stringify(params, {addQueryPrefix: true});
location.href详解
location.href属性表示当前页面的完整URL。它可以被用来获取当前页面的URL、设置当前页面的URL,或者在当前页面和另一个页面之间导航。
location.href的语法如下:
location.href = "URL"
其中,URL是目标URL的字符串。
location.href属性具有以下几个特点:
- 它是一个只读属性,只能被获取,不能被设置。
- 它是一个字符串,包含当前页面的完整URL。
- 它是一个相对URL,不包含协议和主机名。
- 它是一个动态属性,当页面加载时,它的值会自动更新。
location.href属性可以被用来执行以下操作:
- 获取当前页面的URL。
const url = location.href;
- 设置当前页面的URL。
location.href = "https://example.com";
- 在当前页面和另一个页面之间导航。
location.href = "https://example.com/page2";
总结
在本文中,我们介绍了js如何获取url参数,向url字符串追加参数,并详细讲解了location.href的使用方法。我们提供了丰富的示例和代码片段,帮助您更好地理解和应用这些知识。