Append to Query String JavaScript - javascript

When I'm trying to append an id to the end of my query string, the JS adds unnecessary ampersand and '=' sign to the query string.
I'm trying to go for something like this:
http://sample_site/report/file/list?f%5B%5D=1111
but I get this when I view the result in the console:
http://sample_site/report/file/list?f%5B%5D=&f=1111
Here is my JS function that builds a URL object:
buildTileFilter(){
let url = new URL('http://sample_site/report/file/list?f%5B%5D');
let query_string = url.search;
let search_params = new URLSearchParams(query_string);
search_params.set('f', 1111);
url.search = search_params.toString();
let new_url = url.toString();
return new_url;
}

The "%5B%5D" part is being treated as part of the parameter name. You have to add it to the param name that you're setting to get the result you want. That's the encoded value for the string "[]", so to get your result, the code should be:
buildTileFilter(){
let url = new URL('http://sample_site/report/file/list?f%5B%5D');
let query_string = url.search;
let search_params = new URLSearchParams(query_string);
search_params.set('f[]', 1111);
url.search = search_params.toString();
let new_url = url.toString();
return new_url;
}

Related

How to get an array from the URL? [duplicate]

This question already has answers here:
Get the values from the "GET" parameters (JavaScript) [duplicate]
(63 answers)
How can I convert a comma-separated string to an array?
(19 answers)
How to obtain the query string from the current URL with JavaScript?
(19 answers)
Closed 4 years ago.
I have put an array into my URL like this:
var params = arrayitems.join('&');
var url = "https://www.example.com/page?="+params;
So the URL looks like this:
https://www.example.com/page?=item1&item2&item3&item4&item5
Now does anyone know how I can then put these items back into an array on the next page?
Thanks!
You can split them back by page?= and than &
let arrayitems = ['item1','item2','item3','item4','item5']
var params = arrayitems.join('&');
var url = "https://www.example.com/page?="+params;
let arrayBack = url.split('page?=')[1].split('&')
console.log(arrayBack)
URL Object:
Use URL to get the data you need from the search parameters.
URL is used to parse, construct, normalise, and encode URLs.
The URL object has a very convenient method called searchParams
The searchParams readonly property of the URL interface returns a
URLSearchParams object allowing access to the GET decoded query
arguments contained in the URL.
Quick solution:
not recommended... but works
Since your query parameters are not valid (no key, just values) an extra step is required to get the values.
const url = new URL('https://www.example.com/page?=item1&item2&item3&item4&item5');
const res = [...url.searchParams]
.flat()
.filter(v=>v!==null&&v.length>0);
console.log(res);
Better solution using valid URL:
It would be better if you instead organised your URL the following way, so that your url string would look like
https://www.example.com/page?item=item1&item=item2&item=item3
const params = ['item1','item2','item3']
.map(v=>'item='+v)
.join('&');
const urlStr = "https://www.example.com/page?"+params;
const url = new URL(urlStr);
//Two possible ways of getting the values
//Option 1
const resOption1 = url.searchParams.getAll('item');
//Option 2
const resOption2 = [...url.searchParams.values()];
console.log(resOption1);
console.log(resOption2);
JavaScript:
// Create the object which is an array
var output = new objPropertyAndValues;
var TempArray=[]; // blank array
// Lets grab the URL (windows.location.href)
var url_string = window.location.href;
var url = new URL(url_string);
//We now have URL as an object to read from.
//Lets turn the searchParams into a string which we can then split into an Array
var urlParamsString = url.searchParams.toString();
//Now lets split urlParamsString into an array
var AllParamsFound = urlParamsString.split("&");
// Lets read each array item by doing a loop
// We then split the array item value by the "=" sign to split parameter and value
for (i = 0; i < AllParamsFound .length; i++){
TempArray= AllParamsFound [i].split("=");
output.Property[i] = TempArray[0];
output.Value[i] = TempArray[1];
}
console.log(output);
//We allow an object to be created.
function objPropertyAndValues(){
this.Property = [];
this.Value = [];
}
Running Example:
// Create the object which is an array
var output = new objPropertyAndValues;
var TempArray=[]; // blank array
// Lets grab the URL (windows.location.href)
var url_string = "http://www.google.com?myName=Datacure&AnswerID=54379924&Likes=Pizza";
var url = new URL(url_string);
//We now have URL as an object to read from.
//Lets turn the searchParams into a string which we can then split into an Array
var urlParamsString = url.searchParams.toString();
//Now lets split urlParamsString into an array
var AllParamsFound = urlParamsString.split("&");
// Lets read each array item by doing a loop
// We then split the array item value by the "=" sign to split parameter and value
for (i = 0; i < AllParamsFound .length; i++){
TempArray= AllParamsFound [i].split("=");
output.Parameter[i] = TempArray[0];
output.Value[i] = TempArray[1];
}
// Example output
console.log (output.Value[0] + " should get " + output.Value[2] + " for answering question id: " + output.Value[1]);
// View the array
console.log(output);
//We allow an object to be created.
function objPropertyAndValues(){
this.Parameter = [];
this.Value = [];
}

Getting URL parameters and filter out a specific parameter

I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);

Remove one of URL query strings which passed to URL as array?

Here is the URL :
www.example.com/?param%5B%5D=A&param%5B%5D=B
the %5B%5D part is [] to pass param as an array, which is encoded in url.
Now, I want to remove one of parameters , desired output is:
www.example.com/?param%5B%5D=B
I have searched for this but found nothing!
All the answers are about removing a single value parameter, not multiple.
UPDATE:
I don't know the exact position of the parameter, i.e the URL could be something like this:
www.example.com/?test=124&test2=456&param%5B%5D=A&param%5B%5D=B
You can take advantage of URL WebAPI.
https://developer.mozilla.org/en-US/docs/Web/API/URL
var base = 'http://www.example.com/'
var query = '?param%5B%5D=A&param%5B%5D=B';
var url = new URL(base + query);
var params = new URLSearchParams(url.search);
var filteredParams = params.getAll('param[]')
.filter(function(el) {
return el !== "A";
}).map(function(el){
return ['param[]', el];
});
var newParams = new URLSearchParams(filteredParams);
var url = new URL(base + '?' + newParams.toString() );
console.log(url.toString());
Here is an example on how to extract the params from the URL.
Now how to use them on a user user interaction form (UI) is up to you.
// Use this to get the document location:
var ActualURL = document.location.href;
console.log("This snippet URL: "+ActualURL);
// Only for this demo, I "simulate" a URL.
// ActualURL is overwritten here.
var ActualURL = "www.example.com/?param%5B%5D=A&param%5B%5D=B";
console.log("FAKED URL: "+ActualURL);
var domain = ActualURL.split("?")[0];
console.log("Domain: "+domain);
var params = ActualURL.split("?")[1];
var param_array = params.split("&");
for (i=0;i<param_array.length;i++){
console.log( "Param #"+i+": "+param_array[i] );
}
console.log("Rebuilted URL with only param #2: "+domain+"?"+param_array[1]);

Replace value of id in URL

I have URLs of that form:
https://www.merkel.com/obama?trump=15&id=9616071454&hilarry=es
I would like, via javascript to replace 9616071454 with 1, for example.
I know about the replace(), but this will replace "id" itself, not the value of "id".
Is there anything common in the web dev world? :)
The solution considering situations when:
id param can contain other characters besides digits
avoiding fragment # replacement when id is followed by #
var str = 'https://www.foo.com/bar?trump=15&hilarry=es&id=961607some1454text#fragment',
newId = 1,
replaced = str.replace(/\bid=[^&#]+/g, "id=" + newId);
console.log(replaced); // "https://www.foo.com/bar?trump=15&hilarry=es&id=1#fragment"
Simply hard-code that &id= to be re-replaced.
var str = 'https://www.merkel.com/obama?trump=15&id=9616071454&hilarry=es';
var str2 = 'https://www.merkel.com/obama?id=9616071454&trump=15&hilarry=es';
var newId = '123';
str = str.replace(/([&?])id=[0-9]+/, '$1id=' + newId);
str2 = str2.replace(/([&?])id=[0-9]+/, '$1id=' + newId);
alert(str);
alert(str2);
Its simple pattern matching. You can refer to this URL about pattern matching.
function(newValue,url) {
url=url.replace(/id=\d+/,'id='+newValue);
return url;
}
This function works and it allows you to pick way parameter you want.
var exampleStrng ='trump=15&id=9616071454&hilarry=es'; // this is an example query string.
var urlQry = window.document.location.search.substring(1); // you can use this in live code to get the query string.
// reusable function for split in text.
function strSpliter( str, splitVal ){
return str.split(splitVal);
}
// function to reassign query parameter values.
function changQry(qry, setParam, chngVal){
var pnt = strSpliter(qry, '&'),//use the spliter function to change the query into an array split on the '&' character.
newQryArr = [], // a temp array to hold the new parameters and their value.
newQry = '',// this will be the string where the query parameters and values are reconstructed into a string.
newQryStr = '';// this will be the query with the new value.
pnt.forEach( function( item, idx ){
var param = strSpliter(item, '='); //use the spliter function to split the parameter and their value.
// checks the parameter against the one you want to change.
if( param[0] === setParam ){
param[1] = chngVal;// assigns the new value to the parameter.
newQryArr.push(param.join('=')); // rejoins the parameter and its value and pushes it into the temp array.
} else {
newQryArr.push(param.join('='));// rejoins the parameter and its value and pushes it into the temp array.
}
newQry = newQryArr.join('&');// rejoins all the parameters and their values.
newQryStr = '?' + newQry;// creates the new query string.
});
return newQryStr; // returns the new search query string.
}
changQry(exampleStrng, 'id', 77777745);
without comments
var urlQry = window.document.location.search.substring(1);
function strSpliter( str, splitVal ){
return str.split(splitVal);
}
function changQry(qry, setParam, chngVal){
var pnt = strSpliter(qry, '&'),
newQryArr = [],
newQry = '',
newQryStr = '';
pnt.forEach( function( item, idx ){
var param = strSpliter(item, '=');
if( param[0] === setParam ){
param[1] = chngVal;
newQryArr.push(param.join('='));
} else {
newQryArr.push(param.join('='));
}
newQry = newQryArr.join('&');
newQryStr = '?' + newQry;
});
return newQryStr;
}
changQry(urlQry, 'id', 77777745);

how to parse a URL parameters in javascript?

In Javascript, how can I get the parameters of a URL string (not the current URL)?
http://localhost:8080/feasthunt/changePassword.html?TOKEN=0FA3267F-0C62-B1C9-DB71-76F6829671ED
can i get token in JSON object?
No need for a 'JSON' object, and just use split to grab it, since its after a '='
var url = 'http://localhost:8080/feasthunt/changePassword.html? TOKEN=0FA3267F-0C62-B1C9-DB71-76F6829671ED';
var token = url.split('=').pop();
//token is equal to: "0FA3267F-0C62-B1C9-DB71-76F6829671ED"
https://jsbin.com/siyazo/1/edit?js,console
try this
var str = "http://localhost:8080/feasthunt/changePassword.html?TOKEN=0FA3267F-0C62-B1C9-DB71-76F6829671ED";
var tokenValue = str.substring(str.indexOf("?")+1).split("=")[1];
Or more generic
var paramMap = {}; str.substring(str.indexOf("?")+1).split("&").forEach(function(val){
var param = val.split("=");
paramMap[param[0]] = param[1];
})
paramMap is your JSON object, where paramMap["TOKEN"] will give you the value for this param

Categories