我有这个URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
我需要的是能够改变'行' url参数值我指定的东西,让我们说10。如果“行”不存在,我需要将它添加到url的末尾,并添加我已经指定的值(10)。
我有这个URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
我需要的是能够改变'行' url参数值我指定的东西,让我们说10。如果“行”不存在,我需要将它添加到url的末尾,并添加我已经指定的值(10)。
当前回答
下面是一个使用query-string库的简单解决方案。
const qs = require('query-string')
function addQuery(key, value) {
const q = qs.parse(location.search)
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
// if you are using Turbolinks
// add this: Turbolinks.visit(url)
}
// Usage
addQuery('page', 2)
如果你使用react而不使用react-router
export function useAddQuery() {
const location = window.location;
const addQuery = useCallback(
(key, value) => {
const q = qs.parse(location.search);
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
},
[location]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
如果你使用react和react-router
export function useAddQuery() {
const location = useLocation();
const history = useHistory();
const addQuery = useCallback(
(key, value) => {
let pathname = location.pathname;
let searchParams = new URLSearchParams(location.search);
searchParams.set(key, value);
history.push({
pathname: pathname,
search: searchParams.toString()
});
},
[location, history]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
PS: qs是从query-string模块导入的。
其他回答
快速的纯js小解决方案,不需要插件:
function replaceQueryParam(param, newval, search) {
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
}
这样叫它:
window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)
或者,如果你想保持在同一页上并替换多个参数:
var str = window.location.search
str = replaceQueryParam('rows', 55, str)
str = replaceQueryParam('cols', 'no', str)
window.location = window.location.pathname + str
Luke:要完全删除参数,为值传递false或null: replaceQueryParam('rows', false, params)。因为0也是假的,所以指定'0'。
我只是写了一个简单的模块来处理读取和更新当前url查询参数。
使用示例:
import UrlParams from './UrlParams'
UrlParams.remove('foo') //removes all occurences of foo=?
UrlParams.set('foo', 'bar') //set all occurences of foo equal to bar
UrlParams.add('foo', 'bar2') //add bar2 to foo result: foo=bar&foo=bar2
UrlParams.get('foo') //returns bar
UrlParams.get('foo', true) //returns [bar, bar2]
下面是我的代码UrlParams.(js/ts):
class UrlParams {
/**
* Get params from current url
*
* @returns URLSearchParams
*/
static getParams(){
let url = new URL(window.location.href)
return new URLSearchParams(url.search.slice(1))
}
/**
* Update current url with params
*
* @param params URLSearchParams
*/
static update(params){
if(`${params}`){
window.history.replaceState({}, '', `${location.pathname}?${params}`)
} else {
window.history.replaceState({}, '', `${location.pathname}`)
}
}
/**
* Remove key from url query
*
* @param param string
*/
static remove(param){
let params = this.getParams()
if(params.has(param)){
params.delete(param)
this.update(params)
}
}
/**
* Add key value pair to current url
*
* @param key string
* @param value string
*/
static add(key, value){
let params = this.getParams()
params.append(key, value)
this.update(params)
}
/**
* Get value or values of key
*
* @param param string
* @param all string | string[]
*/
static get(param, all=false){
let params = this.getParams()
if(all){
return params.getAll(param)
}
return params.get(param)
}
/**
* Set value of query param
*
* @param key string
* @param value string
*/
static set(key, value){
let params = this.getParams()
params.set(key, value)
this.update(params)
}
}
export default UrlParams
export { UrlParams }
var url = new URL(window.location.href);
var search_params = url.searchParams;
search_params.set("param", value);
url.search = search_params.toString();
var new_url = url.pathname + url.search;
window.history.replaceState({}, '', new_url);
我知道这是一个老问题。我增强了上面的功能,以添加或更新查询参数。仍然是一个纯JS解决方案。
function addOrUpdateQueryParam(param, newval, search) {
var questionIndex = search.indexOf('?');
if (questionIndex < 0) {
search = search + '?';
search = search + param + '=' + newval;
return search;
}
var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
var query = search.replace(regex, "$1").replace(/&$/, '');
var indexOfEquals = query.indexOf('=');
return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
}
下面是一个使用query-string库的简单解决方案。
const qs = require('query-string')
function addQuery(key, value) {
const q = qs.parse(location.search)
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
// if you are using Turbolinks
// add this: Turbolinks.visit(url)
}
// Usage
addQuery('page', 2)
如果你使用react而不使用react-router
export function useAddQuery() {
const location = window.location;
const addQuery = useCallback(
(key, value) => {
const q = qs.parse(location.search);
const url = qs.stringifyUrl(
{
url: location.pathname,
query: {
...q,
[key]: value,
},
},
{ skipEmptyString: true }
);
window.location.href = url
},
[location]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
如果你使用react和react-router
export function useAddQuery() {
const location = useLocation();
const history = useHistory();
const addQuery = useCallback(
(key, value) => {
let pathname = location.pathname;
let searchParams = new URLSearchParams(location.search);
searchParams.set(key, value);
history.push({
pathname: pathname,
search: searchParams.toString()
});
},
[location, history]
);
return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)
PS: qs是从query-string模块导入的。