我有这个网址:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
我需要的是能够将“行”的url参数值更改为我指定的值,比方说10。如果“行”不存在,则需要将其添加到url的末尾并添加我已经指定的值(10)。
我有这个网址:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
我需要的是能够将“行”的url参数值更改为我指定的值,比方说10。如果“行”不存在,则需要将其添加到url的末尾并添加我已经指定的值(10)。
Answers:
我已经扩展了Sujoy的代码以构成一个函数。
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
函数调用:
var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');
window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));
更新的版本也照顾URL上的锚点。
function updateURLParameter(url, param, paramVal)
{
var TheAnchor = null;
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL)
{
var tmpAnchor = additionalURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheAnchor)
additionalURL = TheParams;
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++)
{
if(tempArray[i].split('=')[0] != param)
{
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
else
{
var tmpAnchor = baseURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheParams)
baseURL = TheParams;
}
if(TheAnchor)
paramVal += "#" + TheAnchor;
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
http://www.domain.com/index.php?action=my_action&view-all=Yes
,我需要更改“ view-all”值。我的SO问题已关闭:stackoverflow.com/questions/13025880/...
window.location.pathname
。
在学到了很多东西之后,四年后回答我自己的问题。特别是您不应该对所有内容都使用jQuery。我创建了一个可以解析/字符串化查询字符串的简单模块。这使得修改查询字符串变得容易。
您可以按以下方式使用查询字符串:
// parse the query string into an object
var q = queryString.parse(location.search);
// set the `row` property
q.rows = 10;
// convert the object to a query string
// and overwrite the existing query string
location.search = queryString.stringify(q);
纯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'
。
Ben Alman 在这里有一个不错的jquery querystring / url插件,可让您轻松地操纵querystring。
按照要求 -
在此处转到他的测试页
在firebug中,将以下内容输入到控制台中
jQuery.param.querystring(window.location.href, 'a=3&newValue=100');
它将返回以下修改的URL字符串
http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3
请注意,a的查询字符串值已从X更改为3,并添加了新值。
然后,您可以根据需要使用新的url字符串,例如,使用document.location = newUrl或更改锚链接等
TypeError: jQuery.param.querystring is not a function
jQuery.param.querystring
。我想他们已经重构了图书馆。
一种现代的方法是使用基于本地标准的URLSearchParams。它是由所有主流浏览器的支持,除了IE,他们正在polyfills 可用
const paramsString = "site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc"
const searchParams = new URLSearchParams(paramsString);
searchParams.set('rows', 10);
console.log(searchParams.toString()); // return modified string.
site.fwx%3Fposition=1&archiveid=5000&columns=5&rows=10&sorting=ModifiedTimeAsc
令人困惑,因为如果您手动进行操作,这将不是您要构建的结果……
你也可以通过普通的JS来做
var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1];
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
if(tempArray[i].indexOf("rows") == -1){
newAdditionalURL += temp+tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;
这是更改URL参数的现代方法:
function setGetParam(key,value) {
if (history.pushState) {
var params = new URLSearchParams(window.location.search);
params.set(key, value);
var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.toString();
window.history.pushState({path:newUrl},'',newUrl);
}
}
替代String操作的可行选择是设置html form
并仅修改rows
元素吗?
所以,html
这就像
<form id='myForm' target='site.fwx'>
<input type='hidden' name='position' value='1'/>
<input type='hidden' name='archiveid' value='5000'/>
<input type='hidden' name='columns' value='5'/>
<input type='hidden' name='rows' value='20'/>
<input type='hidden' name='sorting' value='ModifiedTimeAsc'/>
</form>
用以下JavaScript提交表单
var myForm = document.getElementById('myForm');
myForm.rows.value = yourNewValue;
myForm.submit();
可能不适合所有情况,但可能比解析URL字符串更好。
您可以使用我的库来完成此工作:https : //github.com/Mikhus/jsurl
var url = new Url('site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc');
url.query.rows = 10;
alert( url);
2020解决方案:设置变量或删除iti(如果您通过null
或undefined
给该值)。
var setSearchParam = function(key, value) {
if (!window.history.pushState) {
return;
}
if (!key) {
return;
}
var url = new URL(window.location.href);
var params = new window.URLSearchParams(window.location.search);
if (value === undefined || value === null) {
params.delete(key);
} else {
params.set(key, value);
}
url.search = params;
url = url.toString();
window.history.replaceState({url: url}, null, url);
}
URLSearchParams
不适用于所有主流浏览器的最新版本(2020)
我编写了一个与任何选择一起使用的辅助函数。您需要做的就是将class“ redirectOnChange”添加到任何select元素,这将导致页面使用新的/更改后的querystring参数重新加载,该参数等于select的ID和值,例如:
<select id="myValue" class="redirectOnChange">
<option value="222">test222</option>
<option value="333">test333</option>
</select>
上面的示例将添加“?myValue = 222”或“?myValue = 333”(如果存在其他参数,则使用“&”),然后重新加载页面。
jQuery的:
$(document).ready(function () {
//Redirect on Change
$(".redirectOnChange").change(function () {
var href = window.location.href.substring(0, window.location.href.indexOf('?'));
var qs = window.location.href.substring(window.location.href.indexOf('?') + 1, window.location.href.length);
var newParam = $(this).attr("id") + '=' + $(this).val();
if (qs.indexOf($(this).attr("id") + '=') == -1) {
if (qs == '') {
qs = '?'
}
else {
qs = qs + '&'
}
qs = qs + newParam;
}
else {
var start = qs.indexOf($(this).attr("id") + "=");
var end = qs.indexOf("&", start);
if (end == -1) {
end = qs.length;
}
var curParam = qs.substring(start, end);
qs = qs.replace(curParam, newParam);
}
window.location.replace(href + '?' + qs);
});
});
在这里,我接受了阿迪尔·马利克(Adil Malik)的回答,并修复了与之相关的三个问题。
/**
* Adds or updates a URL parameter.
*
* @param {string} url the URL to modify
* @param {string} param the name of the parameter
* @param {string} paramVal the new value for the parameter
* @return {string} the updated URL
*/
self.setParameter = function (url, param, paramVal){
// http://stackoverflow.com/a/10997390/2391566
var parts = url.split('?');
var baseUrl = parts[0];
var oldQueryString = parts[1];
var newParameters = [];
if (oldQueryString) {
var oldParameters = oldQueryString.split('&');
for (var i = 0; i < oldParameters.length; i++) {
if(oldParameters[i].split('=')[0] != param) {
newParameters.push(oldParameters[i]);
}
}
}
if (paramVal !== '' && paramVal !== null && typeof paramVal !== 'undefined') {
newParameters.push(param + '=' + encodeURI(paramVal));
}
if (newParameters.length > 0) {
return baseUrl + '?' + newParameters.join('&');
} else {
return baseUrl;
}
}
这是我的工作。使用我的editParams()函数,您可以添加,删除或更改任何参数,然后使用内置的replaceState()函数更新URL:
window.history.replaceState('object or string', 'Title', 'page.html' + editParams('sorting', ModifiedTimeAsc));
// background functions below:
// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
key = encodeURI(key);
var params = getSearchParameters();
if (Object.keys(params).length === 0) {
if (value !== false)
return '?' + key + '=' + encodeURI(value);
else
return '';
}
if (value !== false)
params[key] = encodeURI(value);
else
delete params[key];
if (Object.keys(params).length === 0)
return '';
return '?' + $.map(params, function (value, key) {
return key + '=' + value;
}).join('&');
}
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
我的解决方案:
const setParams = (data) => {
if (typeof data !== 'undefined' && typeof data !== 'object') {
return
}
let url = new URL(window.location.href)
const params = new URLSearchParams(url.search)
for (const key of Object.keys(data)) {
if (data[key] == 0) {
params.delete(key)
} else {
params.set(key, data[key])
}
}
url.search = params
url = url.toString()
window.history.replaceState({ url: url }, null, url)
}
然后只需调用“ setParams”并传递一个带有您要设置的数据的对象。
例:
$('select').on('change', e => {
const $this = $(e.currentTarget)
setParams({ $this.attr('name'): $this.val() })
})
就我而言,我必须在其更改时更新html select输入,如果值是“ 0”,请删除该参数。如果对象键也为“ null”,则可以编辑函数并从url中删除参数。
希望这对你们有帮助
Sujoy答案的另一种变化。刚刚更改了变量名称并添加了名称空间包装器:
window.MyNamespace = window.MyNamespace || {};
window.MyNamespace.Uri = window.MyNamespace.Uri || {};
(function (ns) {
ns.SetQueryStringParameter = function(url, parameterName, parameterValue) {
var otherQueryStringParameters = "";
var urlParts = url.split("?");
var baseUrl = urlParts[0];
var queryString = urlParts[1];
var itemSeparator = "";
if (queryString) {
var queryStringParts = queryString.split("&");
for (var i = 0; i < queryStringParts.length; i++){
if(queryStringParts[i].split('=')[0] != parameterName){
otherQueryStringParameters += itemSeparator + queryStringParts[i];
itemSeparator = "&";
}
}
}
var newQueryStringParameter = itemSeparator + parameterName + "=" + parameterValue;
return baseUrl + "?" + otherQueryStringParameters + newQueryStringParameter;
};
})(window.MyNamespace.Uri);
现在的用法是:
var changedUrl = MyNamespace.Uri.SetQueryStringParameter(originalUrl, "CarType", "Ford");
我也写了一个库来获取和设置JavaScript中的URL查询参数。
这是一个用法示例。
var url = Qurl.create()
, query
, foo
;
通过键或添加/更改/删除将查询参数作为对象获取。
// returns { foo: 'bar', baz: 'qux' } for ?foo=bar&baz=qux
query = url.query();
// get the current value of foo
foo = url.query('foo');
// set ?foo=bar&baz=qux
url.query('foo', 'bar');
url.query('baz', 'qux');
// unset foo, leaving ?baz=qux
url.query('foo', false); // unsets foo
我正在寻找相同的东西并发现:https : //github.com/medialize/URI.js,这是非常好的:)
-更新
我找到了一个更好的包:https : //www.npmjs.org/package/qs它也处理get参数中的数组。
我知道这是一个老问题。我已经增强了上面的功能来添加或更新查询参数。仍然只是纯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 : '');
}
我的功能支持删除参数
function updateURLParameter(url, param, paramVal, remove = false) {
var newAdditionalURL = '';
var tempArray = url.split('?');
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var rows_txt = '';
if (additionalURL)
newAdditionalURL = decodeURI(additionalURL) + '&';
if (remove)
newAdditionalURL = newAdditionalURL.replace(param + '=' + paramVal, '');
else
rows_txt = param + '=' + paramVal;
window.history.replaceState('', '', (baseURL + "?" + newAdditionalURL + rows_txt).replace('?&', '?').replace('&&', '&').replace(/\&$/, ''));
}
我刚刚编写了一个简单的模块来处理读取和更新当前的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 }
// usage: clear ; cd src/js/node/js-unit-tests/01-set-url-param ; npm test ; cd -
// prereqs: , nodejs , mocha
// URI = scheme:[//authority]path[?paramName1=paramValue1¶mName2=paramValue2][#fragment]
// call by: uri = uri.setUriParam("as","md")
String.prototype.setUriParam = function (paramName, paramValue) {
var uri = this
var fragment = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
uri = ( uri.indexOf('#') === -1 ) ? uri : uri.split('#')[0]
if ( uri.indexOf("?") === -1 ) { uri = uri + '?&' }
uri = uri.replace ( '?' + paramName , '?&' + paramName)
var toRepl = (paramValue != null) ? ('$1' + paramValue) : ''
var toSrch = new RegExp('([&]' + paramName + '=)(([^&#]*)?)')
uri = uri.replace(toSrch,toRepl)
if (uri.indexOf(paramName + '=') === -1 && toRepl != '' ) {
var ampersandMayBe = uri.endsWith('&') ? '' : '&'
uri = uri + ampersandMayBe + paramName + "=" + String(paramValue)
}
uri = ( fragment.length == 0 ) ? uri : (uri+"#"+fragment) //may-be re-add the fragment
return uri
}
var assert = require('assert');
describe('replacing url param value', function () {
// scheme://authority/path[?p1=v1&p2=v2#fragment
// a clean url
it('http://org.com/path -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? with num value
it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=57'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? but string value
it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=boo-bar'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=boo-bar-baz'
var uriActual = uri.setUriParam("bid","boo-bar-baz")
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ?& but string value
it('http://org.com/path?&prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? with other param
it('http://org.com/path?prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ?& with other param
it('http://org.com/path?&prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ? with other param with fragment
it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v#f'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// has the url param existing after the ?& with other param with fragment
it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v#f'
var uriActual = uri.setUriParam("bid",10)
assert.equal(uriActual, uriExpected);
});
// remove the param-name , param-value pair
it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
var uriActual = uri.setUriParam("bid",null)
assert.equal(uriActual, uriExpected);
});
// remove the param-name , param-value pair
it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
var uriActual = uri.setUriParam("bid",null)
assert.equal(uriActual, uriExpected);
});
// add a new param name , param value pair
it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v&bid=foo-bar#f'
var uriActual = uri.setUriParam("bid","foo-bar")
assert.equal(uriActual, uriExpected);
});
});