javascript: how to modify the query string? - javascript

Like
?a=1&b=2&c=3
I only want to change b=6 while keep the other things the same, how to do it?

Following function if you have to replace any b=XXX with b=newBValue
function ReplaceB(strQuery,newBValue)
{
var idxStart= strQuery.indexOf("b=")
if(idxStart<0)
return; // b= not found, nothing to change
var idxFin=strQuery.substr(0,idxStart).indexOf("&");
var newQuery;
if(idxFin<0)
newQuery = strQuery.substr(0,idxStart) + "b="+newBValue
else
newQuery = strQuery.substr(0,idxStart) + "b="+newBValue+strQuery.substr(idxStart+idxFin)
return newQuery;
}

here a small function to do this:
jQuery.replaceURLParam = function (oldURL, replaceParam, newVal) {
var iStart = oldURL .indexOf(replaceParam + '=');
var iEnd = oldURL .substring(iStart + 1).indexOf('&');
var sEnd = oldURL .substring(iStart + iEnd + 1);
var sStart = oldURL .substring(0, iStart);
var newURl = sStart + replaceParam + '=' + newVal;
if (iEnd > 0) {
newURl += sEnd;
}
return newURl;
}
document.body.innerHTML = jQuery.replaceURLParam('www.foo.com?a=1&b=2&c=3', 'b', 6) ;
demo: http://jsfiddle.net/3rkrn/

var queryStr = "?a=1&b=2&c=3";
var startTag = "b=";
var endTag = "&";
var index1 = queryStr.indexOf(startTag) + startTag.length;
var index2 = queryStr.indexOf(endTag,index1);
var newValue = 23;
queryStr = queryStr.substr(0, index1) + newValue + queryStr.substr(index2);
alert(queryStr);
See it here : http://jsfiddle.net/aQL8p/

var test = "?a=1&b=2&c=3".replace(/b=2/gi,"b=6");
alert(test);
Example
var test = "?a=1&b=2&c=3".replace("b=2","b=6");
alert(test);
Example
var test = "?a=1&b=2&c=3".split("b=2").join("b=6");
alert(test);
Example
Regardless of Number
Want to change to value of b regardless of number it is already? Use:
var test = "?a=1&b=2&c=3".replace(/b=\d/gi, "b=6");
alert(test);
Example

var queryString = '?a=1&b=2&c=3'.replace(/([?&;])b=2([$&;])/g, '$1b=6$2');
jsFiddle.
(JavaScript regex does not support lookbehinds).

See if this works for you - a more or less universal urlFor:
https://gist.github.com/4108452
You would simply do
newUrl = urlFor(oldUrl, {b:6});

Related

JavaScript regex.exec() should intended to use an assembled regEx

if I use ( https://jsfiddle.net/fgsvzn4a/ ) :
var text = "ui1pu";
var regExParameter = '\d+';
var regEx = '/(.*)' + regExParameter + '(.*)/gi';
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
i get this error:
Paused on exception
TypeError: regEx.exec is not a function
this prototype is working (inspired by https://stackoverflow.com/a/15845184/2891692 ):
var text = "my1bla";
var matches = /(my)\d+(.*)/gi.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
alert(newStr);
}
but i want to use input parameters to build the regex (first example).
i get ReferenceError: Regex is not defined if i try this:
var text = "ui1pu";
var regExParameter = '\d+';
var regExString = '/(.*)' + regExParameter + '(.*)/gi';
var regEx = new Regex(regExString);
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
any idea?
Use the RegExp constructor. Note that the slashes should be omitted from the string and the flags should be passed as the second argument.
var text = "ui1pu";
var regExParameter = '\\d+';
var regExString = '(.*)' + regExParameter + '(.*)';
var regEx = new RegExp(regExString, 'gi');
var matches = regEx.exec(text);
if(matches && matches[1]) {
var str1 = matches[1];
var str2 = matches[2];
var newStr = str1 + str2
console.log(newStr);
}
Based on the previous correct answers, I was able to come up with this more comprehensive solution. Its a little modification of this correct answer by Unmitigated and all answers :
// window.replaceDOM = function (regExParameter, replaceParameter) {
function replaceDOM(regExParameter, replaceParameter) {
// let reg = '/' + search + '/';
// regExParameter = '\\d+';
console.log('regExParameter=' + regExParameter);
const regExString = '(\\w+)' + regExParameter + '(\\w+)'; // ugly but needet. that escape, that double backslash
console.log('regExString=' + regExString);
const regEx = new RegExp(regExString, 'gi');
let elems = document.body.getElementsByTagName("*");
for (i in elems) {
let ele = elems[i];
if(ele.classList){
const val = ele.classList.value;
if(!val)
continue;
const matches = regEx.exec(val);
if(matches && matches[1]) {
console.log('val=' + val);
const str1 = matches[1];
const str2 = matches[2];
const valNew = str1 + replaceParameter + str2
// alert(valNew);
console.log('valNew=' + valNew);
ele.classList.value = ele.classList.value.replace(val, valNew);
}
}
};
}
.my1bla {
background-color: black;
}
.mybla {
background-color: blue;
}
<button onclick="replaceDOM('y\\d+','y')">
change the style class from DIV using regEx</button>
<div class="my1bla">
I am a DIV element
</div>

Creating dynamic variable in JavaScript for URLs

My current variable 'theurl' has a given static URL. I'd like to pass through URLs through the variable. The main issue is that the URL that i want are created through entering a value on a separate website. Is there an way of retrieving the URL this way or is it completely terrible?
The website i want to retrieve the produced URL from is https://cloud.timeedit.net/ltu/web/schedule1/ri1Q7.html#
from there i enter the code 'A0033H' in the search field next to the drop down menu with 'kurs/program' (in swedish) selected.
At the moment I've checked out the passing value between two html pages.
<script type="text/javascript">
var HttpClient = function () {
this.get = function (aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function () {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open("GET", aUrl, true);
anHttpRequest.send(null);
}
}
var theurl = 'https://cloud.timeedit.net/ltu/web/schedule1/ri166XQ2505Z5YQv250132Z6yQY820653YX5Y3gQ3076757.json';
var client = new HttpClient();
client.get(theurl, function (response) {
var response1 = JSON.parse(response);
//alert(response);
var test = JSON.stringify(response);
var test2 = test.replace(/,/g, " ");
var test3 = test2.replace(/}/g, " ");
var test4 = test3.replace(/{/g, " ");
var test5 = test4.replace(/"/g, " ");
var test6 = test5.replace(/ /g, " ");
var test7 = test6.replace(/\\/g, " ");
var test8 = test7.replace(/ \ /g, " ");
var test9 = test8.replace(/\ /g, " ");
var test10 = test9.replace(/]/g, " ");
var test11 = test10.replace(/\[/g, " ");
var test12 = test11.replace(/" "/g, '');
//alert(test12);
// this is the string variable
var wordLength = test12.length; // we use the length method to store the length of the word string in a variable
document.write('<table>');
document.write('<tr><th>Lektioner</th></tr>');
for (i = 0; i < wordLength; i++) {
var indexNr = test12.indexOf('id', i += 100);
var indexNr2 = test12.indexOf('id', i += 200);
//alert(indexNr);
//alert(indexNr2);
var substring = test12.substring(indexNr, indexNr2);
// alert(substring);
var j = 200;
var indexNr4 = test12.indexOf('columns', j += 110);
var indexNr3 = test12.indexOf('id', j += 110);
var substring2 = test12.substring(indexNr4, indexNr3);
document.write('<tr><td>' + substring + '</td></tr>');
}
document.write('</table>');
});
</script>
The produced result gives me the JSON format structured in a table as strings.
I know this is severe spaghetti code, but I'm just wondering if the retrieval of the URL is possible?

How do I make the right conditions for the url based on the value of a variable? (javascript)

My script javascript like this :
<script>
var url = 'http://my-app.test/item';
var sessionBrand = 'honda';
var sessionModel = 'jazz';
var sessionCategory = 'velg';
var sessionKeyword = 'RS 175/60 R 15';
if(sessionBrand)
var brand = '?brand='+sessionBrand;
else
var brand = '';
if(sessionModel)
var model = '&model='+sessionModel;
else
var model = '';
if(sessionCategory)
var category = '&category='+sessionCategory;
else
var category = '';
if(sessionKeyword)
var keyword = '&keyword='+this.sessionKeyword;
else
var keyword = '';
var newUrl = url+brand+model+category+keyword;
console.log(newUrl);
</script>
The result of console.log like this :
http://my-app.test/item?brand=honda&model=jazz&category=velg&keyword=RS 175/60 R 15
var sessionBrand, sessionModel, sessionCategory and sessionKeyword is dynamic. It can change. It can be null or it can have value
I have a problem
For example the case like this :
var sessionBrand = '';
var sessionModel = '';
var sessionCategory = '';
var sessionKeyword = 'RS 175/60 R 15';
The url to be like this :
http://my-app.test/item&keyword=RS 175/60 R 15
Should the url like this :
http://my-app.test/item?keyword=RS 175/60 R 15
I'm still confused to make the condition
How can I solve this problem?
Just use the array for params and then join them with & separator. For example:
var url = 'http://my-app.test/item';
var sessionBrand = 'honda';
var sessionModel = 'jazz';
var sessionCategory = 'velg';
var sessionKeyword = 'RS 175/60 R 15';
var params = [];
if (sessionBrand) {
params.push('brand=' + sessionBrand);
}
if (sessionModel) {
params.push('model=' + sessionModel);
}
if(sessionCategory) {
params.push('category=' + sessionCategory);
}
if(sessionKeyword) {
params.push('category=' + sessionCategory);
}
var newUrl = url + '?' + params.join('&');
console.log(newUrl);
The problem with your code is that it is prefacing all query parameters with a & - except for the sessionBrand. What you need in a URL is for the first parameter to start with a ?, and all others with a &. As you saw, your code doesn't do this when there is no sessionBrand.
There are number of ways to fix this. Probably the neatest I can think of is to assemble the various parts as you are, but without any prefixes - then join them all together at the end. Like this (I just saw Viktor's solution, it's exactly the same idea, but neater because he rewrote more of your earlier code):
if(sessionBrand)
var brand = 'brand='+sessionBrand;
else
var brand = '';
if(sessionModel)
var model = 'model='+sessionModel;
else
var model = '';
if(sessionCategory)
var category = 'category='+sessionCategory;
else
var category = '';
if(sessionKeyword)
var keyword = 'keyword='+this.sessionKeyword;
else
var keyword = '';
var queryString = '?' + [sessionBrand, sessionModel, sessionCategory, sessionKeyword].filter(function(str) {
return str.length > 0;
}).join("&");
var newUrl = url+queryString;

how to change url parameter value in browser [duplicate]

I have this URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
what I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified (10).
I've extended Sujoy's code to make up a function.
/**
* 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;
}
Function Calls:
var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');
window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));
Updated version that also take care of the anchors on the 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;
}
I think you want the query plugin.
E.g.:
window.location.search = jQuery.query.set("rows", 10);
This will work regardless of the current state of rows.
Quick little solution in pure js, no plugins needed:
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 : '');
}
Call it like this:
window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)
Or, if you want to stay on the same page and replace multiple params:
var str = window.location.search
str = replaceQueryParam('rows', 55, str)
str = replaceQueryParam('cols', 'no', str)
window.location = window.location.pathname + str
edit, thanks Luke: To remove the parameter entirely, pass false or null for the value: replaceQueryParam('rows', false, params). Since 0 is also falsy, specify '0'.
To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.
You can use query-string as follows:
// 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);
A modern approach to this is to use native standard based URLSearchParams. It's supported by all major browsers, except for IE where they're polyfills available
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.
Ben Alman has a good jquery querystring/url plugin here that allows you to manipulate the querystring easily.
As requested -
Goto his test page here
In firebug enter the following into the console
jQuery.param.querystring(window.location.href, 'a=3&newValue=100');
It will return you the following amended url string
http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3
Notice the a querystring value for a has changed from X to 3 and it has added the new value.
You can then use the new url string however you wish e.g
using document.location = newUrl or change an anchor link etc
This is the modern way to change URL parameters:
function setGetParam(key,value) {
if (history.pushState) {
var params = new URLSearchParams(window.location.search);
params.set(key, value);
var newUrl = window.location.origin
+ window.location.pathname
+ '?' + params.toString();
window.history.pushState({path:newUrl},'',newUrl);
}
}
you can do it via normal JS also
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;
Use URLSearchParams to check, get and set the parameters value into URL
Here is the example to get the current URL and set new parameter and update the URL or reload the page as per your needs
var rows = 5; // value that you want to set
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
url.search = url.searchParams;
url = url.toString();
// if you want to append into URL without reloading the page
history.pushState({}, null, url);
// want to reload the window with a new param
window.location = url;
2020 Solution: sets the variable or removes iti if you pass null or undefined to the value.
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);
}
Would a viable alternative to String manipulation be to set up an html form and just modify the value of the rows element?
So, with html that is something like
<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>
With the following JavaScript to submit the form
var myForm = document.getElementById('myForm');
myForm.rows.value = yourNewValue;
myForm.submit();
Probably not suitable for all situations, but might be nicer than parsing the URL string.
URL query parameters can be easily modified using URLSearchParams and History interfaces:
// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
// Set new or modify existing parameter value.
//queryParams.set("myParam", "myValue");
queryParams.set("rows", "10");
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());
Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:
history.pushState(null, null, "?"+queryParams.toString());
https://zgadzaj.com/development/javascript/how-to-change-url-query-parameter-with-javascript-only
You can use this my library to do the job: 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);
Consider this one:
const myUrl = new URL("http://www.example.com?columns=5&rows=20");
myUrl.searchParams.set('rows', 10);
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10
myUrl.searchParams.set('foo', 'bar'); // add new param
console.log(myUrl.href); // http://www.example.com?columns=5&rows=10&foo=bar
It will do exactly the same thing you required. Please note URL must have correct format. In your example you have to specify protocol (either http or https)
I wrote a little helper function that works with any select. All you need to do is add the class "redirectOnChange" to any select element, and this will cause the page to reload with a new/changed querystring parameter, equal to the id and value of the select, e.g:
<select id="myValue" class="redirectOnChange">
<option value="222">test222</option>
<option value="333">test333</option>
</select>
The above example would add "?myValue=222" or "?myValue=333" (or using "&" if other params exist), and reload the page.
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);
});
});
Using javascript URL:
var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
window.location = url;
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);
Here I have taken Adil Malik's answer and fixed the 3 issues I identified with it.
/**
* 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;
}
}
In the URLSearchParams documentation, there's a very clean way of doing this, without affecting the history stack.
// URL: https://example.com?version=1.0
const params = new URLSearchParams(location.search);
params.set('version', 2.0);
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?version=2.0
Similarily, to remove a parameter
params.delete('version')
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?
let url= new URL("https://example.com/site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc")
url.searchParams.set('rows', 10)
console.log(url.toString())
Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the 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;
}
My solution:
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)
}
Then just call "setParams" and pass an object with data you want to set.
Example:
$('select').on('change', e => {
const $this = $(e.currentTarget)
setParams({ $this.attr('name'): $this.val() })
})
In my case I had to update a html select input when it changes and if the value is "0", remove the parameter. You can edit the function and remove the parameter from the url if the object key is "null" as well.
Hope this helps yall
If you want to change the url in address bar:
const search = new URLSearchParams(location.search);
search.set('rows', 10);
location.search = search.toString();
Note, changing location.search reloads the page.
Here is a simple solution using the query-string library.
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)
If you are using react without 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)
If you are using react with 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 is the import from query-string module.
Another variation on Sujoy's answer. Just changed the variable names & added a namespace wrapper:
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);
Useage is now:
var changedUrl = MyNamespace.Uri.SetQueryStringParameter(originalUrl, "CarType", "Ford");
I too have written a library for getting and setting URL query parameters in JavaScript.
Here is an example of its usage.
var url = Qurl.create()
, query
, foo
;
Get query params as an object, by key, or add/change/remove.
// 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
I was looking for the same thing and found: https://github.com/medialize/URI.js which is quite nice :)
-- Update
I found a better package: https://www.npmjs.org/package/qs it also deals with arrays in get params.
No library, using URL() WebAPI (https://developer.mozilla.org/en-US/docs/Web/API/URL)
function setURLParameter(url, parameter, value) {
let url = new URL(url);
if (url.searchParams.get(parameter) === value) {
return url;
}
url.searchParams.set(parameter, value);
return url.href;
}
This doesn't work on IE: https://developer.mozilla.org/en-US/docs/Web/API/URL#Browser_compatibility
I know this is an old question. I have enhanced the function above to add or update query params. Still a pure JS solution only.
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 : '');
}
my function support removing param
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(/\&$/, ''));
}

if querystring value exists remove param and reset url

my url looks something like this
/myurl?code1=abcde&code2=fghijk&code3=lmnop&code4=qrstu&code5=vwxyz (up to max of 5 code variables)
I have an onclick event where I get the code variable, eg in example above it returns 'fghijk', but I don't know the param, eg code2. So I want to do two things:
1) find and remove the param & value from my url (if my onclick variable returns 'fghijk', in the above example my url becomes, /myurl?code1=abcde&code3=lmnop&code4=qrstu&code5=vwxyz)
2) after this I want to reset the param numbers so that my code params are sequential beginning from 1, so after number 1 above executes my url should become /myurl?code1=abcde&code2=lmnop&code3=qrstu&code4=vwxyz
$('.myelement').on('click', function() {
var url = $('.myelement a').attr('href');
var codevar = $('.myelement span').text();
if(url +'contains('+codevar+')') {
// strip the param and variable from the url here
// now reset the url so code params are in number sequence
}
});
you could do something like this:
$('.myelement').on('click', function() {
var url = $('.myelement a').attr('href');
var codevar = $('.myelement span').text();
if(url.match(codevar)) {
var queryString = url.substring(url.indexOf("?") + 1);
var params = queryString.split("&");
var codeIndex = 1;
var newQuery = "";
for (var i = 0; i < params.length; i++) {
if (!params[i].match(codevar)) {
newQuery += params[i].replace(/code[0-9]/, "code" + codeIndex);
codeIndex++;
if (i < params.length - 1) {
newQuery += "&";
}
}
}
url = url.replace(queryString, newQuery).replace(/&$/, ""); //new query string with the sequential parameters
}
});
Hope this helps.
Regards,
Marcelo
var codevar = 'fghijk';
var url = $('.myelement a').attr('href');
var param = '&'+url.substring(url.indexOf('?')+1);
url = url.substring(0,url.indexOf('?')+1);
if(param.indexOf(codevar) > -1) {
var arr = param.split("&code");
param = '';
for(var i = 1;i<arr.length;i++){
if(codevar == arr[i].substring(2))
arr.splice(i, 1);
param += 'code'+i+'='+arr[i].substring(2);
if(i != arr.length-1)
param +='&';
}
$('.myelement a').attr('href',url+param);
Example:
http://jsfiddle.net/trevordowdle/b9Hmb/1/
You could split the url with the param as key.
var el = $('.myelement'),
out = $("#output");
el.on('click', function (ev) {
ev.preventDefault();
var href = el.find("a").prop("href"),
param = el.find("span").text(),
idx = href.indexOf(param),
arr = [], url;
if (idx > -1) {
arr = href.split(param); // split href[0] param href[1]
url = arr.join("mynewvalue");
out.text(url);
}
});
DEMO : http://jsfiddle.net/tive/EAsw3/

Categories

Resources