用javascript我怎么能添加一个查询字符串参数的url,如果不存在或如果它存在,更新当前值?我使用jquery为我的客户端开发。
当前回答
这样做的目的是:
function updateQueryString(url, key, value) {
var arr = url.split("#");
var url = arr[0];
var fragmentId = arr[1];
var updatedQS = "";
if (url.indexOf("?") == -1) {
updatedQS = encodeURIComponent(key) + "=" + encodeURIComponent(value);
}
else {
updatedQS = addOrModifyQS(url.substring(url.indexOf("?") + 1), key, value);
}
url = url.substring(0, url.indexOf("?")) + "?" + updatedQS;
if (typeof fragmentId !== 'undefined') {
url = url + "#" + fragmentId;
}
return url;
}
function addOrModifyQS(queryStrings, key, value) {
var oldQueryStrings = queryStrings.split("&");
var newQueryStrings = new Array();
var isNewKey = true;
for (var i in oldQueryStrings) {
var currItem = oldQueryStrings[i];
var searchKey = key + "=";
if (currItem.indexOf(searchKey) != -1) {
currItem = encodeURIComponent(key) + "=" + encodeURIComponent(value);
isNewKey = false;
}
newQueryStrings.push(currItem);
}
if (isNewKey) {
newQueryStrings.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
}
return newQueryStrings.join("&");
}
其他回答
一种不使用正则表达式的不同方法。支持url末尾的“散列”锚以及多个问号字符(?)。应该比正则表达式方法略快。
function setUrlParameter(url, key, value) {
var parts = url.split("#", 2), anchor = parts.length > 1 ? "#" + parts[1] : '';
var query = (url = parts[0]).split("?", 2);
if (query.length === 1)
return url + "?" + key + "=" + value + anchor;
for (var params = query[query.length - 1].split("&"), i = 0; i < params.length; i++)
if (params[i].toLowerCase().startsWith(key.toLowerCase() + "="))
return params[i] = key + "=" + value, query[query.length - 1] = params.join("&"), query.join("?") + anchor;
return url + "&" + key + "=" + value + anchor
}
感谢现代javascript, node.js和浏览器的支持,我们可以摆脱第三方库的漩涡(jquery, query-string等)和DRY自己。
下面是javascript(node.js)和typescript版本的函数,用于添加或更新给定url的查询参数:
Javascript
const getUriWithParam = (baseUrl, params) => { const Url = new URL(baseUrl); const urlParams = new URLSearchParams(Url.search); for (const key in params) { if (params[key] !== undefined) { urlParams.set(key, params[key]); } } Url.search = urlParams.toString(); return Url.toString(); }; console.info('expected: https://example.com/?foo=bar'); console.log(getUriWithParam("https://example.com", {foo: "bar"})); console.info('expected: https://example.com/slug?foo=bar#hash'); console.log(getUriWithParam("https://example.com/slug#hash", {foo: "bar"})); console.info('expected: https://example.com/?bar=baz&foo=bar'); console.log(getUriWithParam("https://example.com?bar=baz", {foo: "bar"})); console.info('expected: https://example.com/?foo=baz&bar=baz'); console.log(getUriWithParam("https://example.com?foo=bar&bar=baz", {foo: "baz"}));
打印稿
const getUriWithParam = (
baseUrl: string,
params: Record<string, any>
): string => {
const Url = new URL(baseUrl);
const urlParams: URLSearchParams = new URLSearchParams(Url.search);
for (const key in params) {
if (params[key] !== undefined) {
urlParams.set(key, params[key]);
}
}
Url.search = urlParams.toString();
return Url.toString();
};
对于React Native
URL在React Native中没有实现。所以你必须事先安装react-native-url-polyfill。
对于对象参数
请看这个答案中的第二个解决方案
我想要的是:
使用浏览器的本地URL API 可以添加、更新、获取或删除吗 期望在散列之后的查询字符串,例如对于单页应用程序
function queryParam(options = {}) { var defaults = { method: 'set', url: window.location.href, key: undefined, value: undefined, } for (var prop in defaults) { options[prop] = typeof options[prop] !== 'undefined' ? options[prop] : defaults[prop] } const existing = (options.url.lastIndexOf('?') > options.url.lastIndexOf('#')) ? options.url.substr(options.url.lastIndexOf('?') + 1) : '' const query = new URLSearchParams(existing) if (options.method === 'set') { query.set(options.key, options.value) return `${options.url.replace(`?${existing}`, '')}?${query.toString()}` } else if (options.method === 'get') { const val = query.get(options.key) let result = val === null ? val : val.toString() return result } else if (options.method === 'delete') { query.delete(options.key) let result = `${options.url.replace(`?${existing}`, '')}?${query.toString()}` const lastChar = result.charAt(result.length - 1) if (lastChar === '?') { result = `${options.url.replace(`?${existing}`, '')}` } return result } } // Usage: let url = 'https://example.com/sandbox/#page/' url = queryParam({ url, method: 'set', key: 'my-first-param', value: 'me' }) console.log(url) url = queryParam({ url, method: 'set', key: 'my-second-param', value: 'you' }) console.log(url) url = queryParam({ url, method: 'set', key: 'my-second-param', value: 'whomever' }) console.log(url) url = queryParam({ url, method: 'delete', key: 'my-first-param' }) console.log(url) const mySecondParam = queryParam({ url, method: 'get', key: 'my-second-param', }) console.log(mySecondParam) url = queryParam({ url, method: 'delete', key: 'my-second-param' }) console.log(url)
如果它没有设置或想要更新一个新值,您可以使用:
window.location.search = 'param=value'; // or param=new_value
这是用简单Javascript写的。
EDIT
你可能想尝试使用jquery查询对象插件
窗口.位置.搜索 = jQuery.query.set(“param”, 5);
给出Gal和tradyblix建议的修改window.location.search的代码示例:
var qs = window.location.search || "?";
var param = key + "=" + value; // remember to URI encode your parameters
if (qs.length > 1) {
// more than just the question mark, so append with ampersand
qs = qs + "&";
}
qs = qs + param;
window.location.search = qs;
推荐文章
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- setTimeout带引号和不带括号的区别
- 在JS的Chrome CPU配置文件中,'self'和'total'之间的差异
- 用javascript检查输入字符串中是否包含数字
- 如何使用JavaScript分割逗号分隔字符串?
- 在Javascript中~~(“双波浪号”)做什么?
- 谷歌chrome扩展::console.log()从后台页面?
- 未捕获的SyntaxError:
- [].slice的解释。调用javascript?
- 在jQuery中的CSS类更改上触发事件
- jQuery日期/时间选择器
- 我如何预填充一个jQuery Datepicker文本框与今天的日期?
- 数组的indexOf函数和findIndex函数的区别
- jQuery添加必要的输入字段