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

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 = [];
}

Related

How I can solve this error in setValues function "The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues" [duplicate]

This question already has answers here:
How do you resolve a "The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues" error
(2 answers)
Closed 8 months ago.
I'm pre-filling a Google form with AppScript, finally I'm saving the urls in an array.
var formCol = SpreadsheetApp.getActive().getRangeByName('FORM');
var form = FormApp.openByUrl(FORM_URL);
var items = form.getItems();
var urls = [];
for (let i = 1; i < 4; i++ ) {
var formResponse = form.createResponse();
var formItem = items[0].asTextItem();
response = formItem.createResponse(botData.id[i]);
formResponse.withItemResponse(response);
formItem = items[1].asTextItem();
response = formItem.createResponse(botData.bot[i]);
formResponse.withItemResponse(response);
var date = new Date (botData.date[i].toString());
var date2 = botData.date[i].toString();
//var day
formItem = items[3].asTextItem();
response = formItem.createResponse(botData.zone[i]);
formResponse.withItemResponse(response);
formItem = items[8].asTextItem();
response = formItem.createResponse(botData.remitent[i]);
formResponse.withItemResponse(response);
formItem = items[9].asTextItem();
response = formItem.createResponse(botData.description[i]);
formResponse.withItemResponse(response);
formItem = items[11].asTextItem();
response = formItem.createResponse(botData.solutiontime[i]);
formResponse.withItemResponse(response);
var url = formResponse.toPrefilledUrl();
//sheet.getRange(row, 31).setValue(url);
url = url.toString()
urls.push(url)
}
formCol.setValues(urls);
}
I want to print each url in a 'FORM' column of Google Sheets but I get the error "
Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues." when I try to print the array with setValues, how I can solve this error?
Modification points:
In your script, urls of formCol.setValues(urls) is 1 dimensional array. The argument of setValues(value) is required to be 2 dimensional array.
When your range of var formCol = SpreadsheetApp.getActive().getRangeByName('FORM'); is used, the size of the range cannot be known. So, in your situation, it might be required to modify the range for putting the values of urls.
When these points are reflected in your script, it becomes as follows.
Modified script:
From:
urls.push(url)
}
formCol.setValues(urls);
To:
urls.push([url]);
}
formCol.setValues(urls);
or
urls.push([url]);
}
formCol.offset(0, 0, urls.length, 1).setValues(urls);
References:
setValues(values)
offset(rowOffset, columnOffset, numRows, numColumns)
It looks like you are passing an argument that is of the wrong type for the setValues function. According to the documentation, you should pass a two dimensional array.

Get all match values from two comma separated string

I have two comma separated string as follows,
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
I need to create another string based on the above two,
if hiddenString have unmatching value with strB,then without those unmatched values need to create e new string and also avoid duplicates.
simply says, I need to get all the matching values from both strings.
As the example based on my two string, I'm expecting the following:
varFinalHiddenString = 14172,10062,100;
How can I do this using JavaScript and that should work in safari and IE 11 or its earlier versions. Please help me, I'm new to the JS.
You can first split() strings to generate arrays from them. Then filter() the smaller array by checking the index of the current item with indexOf() in other array:
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
var temp1 = hiddenString.split(',');
var temp2 = strB.split(',');
var varFinalHiddenString = temp2.filter(function(s){
return temp1.indexOf(s) > -1;
}).join(',');
console.log(varFinalHiddenString);
Make arrays of the strings, then use the "filter" method. Then convert back to string.
var hiddenString = '14172,10062,14172,14172,100,10,14172,15000,12000';
var strB = '14172,10062,10064,10025,100,14182';
var hiddenStringAsArray = hiddenString.split(',');
var strBArray = strB.split(',');
var resultObject = $(strBArray).filter(hiddenStringAsArray);
var resultArray = resultObject.toArray();
var resultString = resultArray.join(',');
console.log(resultString);

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

How to extract a REGEX query string result array into a Javascript object [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Use the get paramater of the url in javascript
How can I get query string values in JavaScript?
In Javascript, how can I get the parameters of a URL string (not the current URL)?
like:
www.domain.com/?v=123&p=hello
Can I get "v" and "p" in a JSON object?
Today (2.5 years after this answer) you can safely use Array.forEach. As #ricosrealm suggests, decodeURIComponent was used in this function.
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
actually it's not that simple, see the peer-review in the comments, especially:
hash based routing (#cmfolio)
array parameters (#user2368055)
proper use of decodeURIComponent and non-encoded = (#AndrewF)
non-encoded + (added by me)
For further details, see MDN article and RFC 3986.
Maybe this should go to codereview SE, but here is safer and regexp-free code:
function getJsonFromUrl(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
var query = question==-1 || hash==question+1 ? url.substring(hash) :
url.substring(question+1,hash);
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
This function can parse even URLs like
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.

user input to URL

I have some url and I need to replace some parts of it with user input from input type="text" and move to new link with button click.
How can I place variables in URL ?
//some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4
i have function, but it place input at the end of url.
function redirect() {
var baseUrl = 'http://google.com.ua/';
document.myform.action=baseUrl + document.getElementById('url').value;
}
<form name="myform" method="post" onsubmit="redirect()">
<input type="text" id="url">
<input type="submit" value="submit">
</form>
You could build out manual query string parsers and constructors, an example would be like:
function parseQuery(qstr){
var query = {};
var a = qstr.split('&'); //take the passed query string and split it on &, creating an array of each value
for (var i in a) { //iterate the array of values
var b = a[i].split('='); //separate the key and value pair
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]); //call decodeURIComponent to sanitize the query string
}
return query; //returned the parsed query string object
}
function buildQuery(obj){
var str = [];
for(var p in obj) //iterate the query object
if (obj.hasOwnProperty(p)) { //check if the object has the propery name we're iterating
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); //push the encoded key value pair from the object into the string array
}
return str.join("&"); //take the array of key value pairs and join them on &
}
Then below we take the string that you gave, for example:
var $str = 'createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4';
Now we call the parseQuery function on our string.
var obj = parseQuery($str);
Then we iterate the object which was produced from our parseQuery function
Object.keys(obj).forEach(function(k, i) {
switch(k){
case 't1':
obj[k] = 'replacedt1';
break;
case 'service':
obj[k] = 'replacedServices';
break;
case 'host':
obj[k] = 'replacedHost';
}
});
Now the obj variable has the newly updated values. We can rebuild the query using our buildQuery function by passing the object in.
console.log(buildQuery(obj));
Which will produce something like:
createimage=undefined&t1=replacedt1&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=replacedHost&service=replacedServices&backtrack=4&zoom=4
As usual, the jsFiddle
You can use the new URL object (for older browsers, there is a polyfill) :
var url = new URL("http://some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4");
url.searchParams.set("t1", "someNewT1");
url.searchParams.set("t2", "someNewT2");
url.searchParams.set("host", "someNewHost");
url.searchParams.set("service", "someNewService");
alert(url.href);
/*
http://some-url/trends.cgi?host=someNewHost&assumestateretention=yes&initialassumedservicestate=0&t2=someNewT2&initialassumedhoststate=0&assumeinitialstates=yes&zoom=4&backtrack=4&createimage=&assumestatesduringnotrunning=yes&includesoftstates=no&service=someNewService&t1=someNewT1
*/
Played with JavaScript a bit, I believe this solves your problem: http://jsfiddle.net/dk48vwz7/
var linktext = "http://site/some-url/trends.cgi?createimage&t1=1412757517&t2=1412843917&assumeinitialstates=yes&assumestatesduringnotrunning=yes&initialassumedhoststate=0&initialassumedservicestate=0&assumestateretention=yes&includesoftstates=no&host=SCP-3&service=MODIFICATION+TIME+EDR+FILES&backtrack=4&zoom=4";
//we'll use an in-memory "hyperlink" object for basic parsing
var anchor = document.createElement("A");
anchor.href=linktext;
//the query string starts with ?, we remove it.
//then, split it by & symbol
var queryvars = anchor.search.replace(/^\?/, '').split('&');
//now looping through all parts of query string, creating an object in form key->value
var querycontent = {};
for( i = 0; i < queryvars.length; i++ ) {
var queryvar = queryvars[i].split('=');
querycontent[queryvar[0]] = queryvar[1];
}
//this allows us to reference parts of the query as properties of "querycontent" variable
querycontent.service = "AnotherService"
//TODO: change the properties you actually need
//and now putting it all back together
var querymerged = [];
var g = "";
for (var key in querycontent){
var fragment = key;
if (querycontent[key]) {
fragment += "=" + querycontent[key];
}
querymerged.push(fragment);
}
anchor.search = querymerged.join("&")
//finally, access the `href` property of anchor to get the link you need
document.getElementById("test").innerText=anchor.href;

Categories