Creating dynamic variable in JavaScript for URLs - javascript

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?

Related

App Script create array from email string

Using app scripts I'm trying to extract all the email addresses from email messages and put them in an array. From my console.log messages, I'm getting stuck because it looks like instead of an array I just get a string. i'm not too familiar with javascript. Any help would be great. I'm looking for an array of email address. The methods of message.get() return a string. I want to split out the email address and create a single, unified array.
var ui = SpreadsheetApp.getUi();
function onOpen(e){
ui.createMenu("Gmail Manager").addItem("Get Emails by Label", "getGmailEmails").addToUi();
}
function getGmailEmails(){
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
var fullArray = [];
for(var i = threads.length - 1; i >=0; i--){
var messages = threads[i].getMessages();
for (var j = 0; j <messages.length; j++){
var message = messages[j];
if (message.isUnread()){
fullArray.push(extractDetails(message));
}
}
}
console.log("FullArray:"+fullArray);
for(var i=0; i<fullArray.length; i++){
console.log("printing array " + i + ": "+fullArray[i])
}
}
function extractDetails(message){
var dateTime = message.getDate();
var subjectText = message.getSubject();
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmail = message.getReplyTo();
var toEmail = message.getTo();
var emailArray = []
var senderArray = senderDetails.split(',');
var ccArray = ccEmails.split(',');
var replyArray = replyEmail.split(',');
var toArray = toEmail.split(',');
for (var i =0 ; i<toArray.length; i++){
console.log("toArray Loop"+ i + " : "+ toArray[i]);
emailArray.push([toArray[i]]);
}
for (var i =0 ; i<ccArray.length; i++){
console.log("ccArray Loop"+ i + " : "+ ccArray[i]);
emailArray.push([ccArray[i]]);
}
console.log("Email Array: "+ emailArray);
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, senderDetails, subjectText, ccEmails,replyEmail,toEmail,emailArray]);
return emailArray;
}
I think the problem is just the console output. If you change console.log("Email Array: "+ emailArray); to console.log("Email Array: ", emailArray);, then it shows an array of arrays. You could simplify your extract method as follows:
function extractDetails(message) {
/* ... */
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmails = message.getReplyTo();
var toEmails = message.getTo();
let emailArray = [senderDetails, ccEmails, replyEmails, toEmails].reduce(
(array, string) => {
//remove names (like "Name <name#company.com>") and filter empty values
let emails = string
.split(/\s*,\s*/)
.map(e => e.replace(/.*?([^#<\s]+#[^#\s>]+).*?/g, "$1"))
.filter(Boolean);
if(emails.length > 0)
return array.concat(emails)
return array
}, []);
/* ... */
}

Node Red multiple values to influxDB

i try with Node Red to build an query to send multiple values to an influxDB from a loop with this code:
var inputArray = msg.payload;
var lenInputArray =inputArray.length;
var modbusStartRegister = 14000;
var sendString = "";
var msg93 ={};
for (i = 0; i < lenInputArray; i++) {
var actRegister = modbusStartRegister +i;
var actValue = inputArray[i];
if ( i >=1){
sendString = sendString + " ,"
}
sendString = sendString +"{register: " + actRegister +"," +"value: " + actValue +"}";
if ( i ==(lenInputArray-1)){
sendString = sendString + "]"
}
}
msg93.payload = sendString;
return msg93
But the insert in the influxDB is one line it looks at them interpreted as an complete string. How can I build or convert the string that the DB accept them as individual entry? Thanks for the help
This is because you are building a string, node an object.
You can build the array object on the fly like this:
var inputArray = msg.payload;
var lenInputArray =inputArray.length;
var modbusStartRegister = 14000;
var payload = [];
var msg93 ={};
for (i = 0; i < lenInputArray; i++) {
var temp = {};
temp.register = modbusStartRegister +i;
temp.value = inputArray[i];
payload.push(temp);
}
msg93.payload = payload;
return msg93

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 empty an Array in a Script

I have a script that uses AJAX/PHP/SQL to query data and pushes it into an array with a bunch of IF's statements. The changeData function is called every 6 seconds. The first query I return I have 6 arrays. The second time i send a request, my push array(IsVacant1) is double and went to 12. after a while, I have over 500 arrays going into my .each statement.
How do I 'clear' this every time I make a request so that I am not adding arrays? Any help is most appreciated.
function changeData() {
isPaused = true;
var mydata0 = null;
$.post('php/ProductionChange.php', {
'WC': cc
}, function(data) { // This is Where I use an AJAX call into a php file.
mydata0 = data; // This takes the array from the call and puts it into a variable
var pa = JSON.parse(mydata0); // This parses the data into arrays and elements
var temp = {};
var bayData = '';
if (pa != null) {
for (var i = 0; i <= pa.length - 1; i++) {
var job = pa[i][0];
var shipdate = pa[i][1];
var status = pa[i][2];
var name = pa[i][3];
var EnclLoc = pa[i][13];
var Enclsize = pa[i][14];
var backpan = pa[i][15];
var percentCom = pa[i][16];
var IsVisible = pa[i][17];
var png = pa[i][18];
var WorkC = pa[i][20];
baydata = 'bayData' + i + '';
temp = {
job, shipdate, name, EnclLoc, Enclsize, backpan, percentCom, IsVisible, png, WorkC, status
};
isVacant1.push({
baydata: temp
});
}
} else {
ii = 1;
//alert("There are no more job numbers in this bay location. Thank you. ");
}
$.each(isVacant1, function(key, value) {
var job = value.baydata.job;
var ship = value.baydata.shipdate;
var name = value.baydata.name;
var encl = value.baydata.EnclLoc;
var EnclSize = value.baydata.EnclLoc;
var percentCom = value.baydata.percentCom;
var backpan = value.baydata.backpan;
var PngLogo = value.baydata.png;
var IsVisible = value.baydata.IsVisible;
var WorkC = value.baydata.WorkC;
var status = value.baydata.status;
var p = WorkC;
WorkC = (WorkC < 10) ? ("0" + WorkC) : WorkC;
//// remember if the encl location matches the workcell cell then do stuff based on that....... hint encl image not hiding becase of duplicate 17s
if (((encl == p) || (backpan == p)) && job != 123) {
$('#WC' + p).show();
document.getElementById("bayData" + p).innerHTML = name + ' ' + ship; // Work Cell Name and Ship Date
document.getElementById("bayData" + p + "a").innerHTML = job; // Work cell Job Number
document.getElementById("percentCom" + p).innerHTML = percentCom + '%'; // Work Cell Percent Complete
} else {
$('#WC' + p).hide();
From your question it looks like you want to clear the isVacant1 array.
In your ajax callback just put isVacant1 = []; as the first line. Like this
function(data) { // This is Where I use an AJAX call into a php file.
isVacant1 = [];
mydata0 = data; // This takes the array from the call and puts it into a variable
var pa = JSON.parse(mydata0); // This parses the data into arrays and elements
var temp = {};
var bayData = '';
..................
From your code it's not clear how you are declaring/initializing isVacant1 so i have suggested isVacant1 = [] otherwise you can also use isVacant1.length = 0.
You can also take a look here How do I empty an array in JavaScript?

javascript: how to modify the query string?

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});

Categories

Resources