I'm trying to have there be a line break between each item in my array. What my program does is create a new array using a few others which are based on the users answer to a question. I can't seem to figure out how to allow a line break between each item.
It's all done in JavaScript (with the exception of a little CSS but unimportant). I've tried using the < br > tag but it would just print the < br > instead.
I have four relevant arrays.
One for the questions:
var questions = ["Do you like volunteering","Would you be interested in joining the musical/theatre?","Would you..."] //it goes on and on but I'll spare you
Another for all of the possible results:
var clubs=[["All In","Interact Club","Key Club"," Environmental Club"],[" Fall Production"," Spring Musical"], "Student Government"," Tricorn"] //also goes on for a while
An empty array called recClubs which gets filled as they make choices.
And an empty array called choices for the choices themselves.
Then a little later I print the final outcome:
function endQuizDiv(){
//header of screen
document.getElementById("question").innerHTML= "These are the clubs that you might be interested in";
//prints the recommended clubs
document.getElementById("recClubs").innerHTML= recClubs;
}
And here is where recClubs gets its information:
function eliminateClubs(){
for(h=0;h<=personChoices.length;h++){
if (personChoices[h]==1){
recClubs.push(clubs[h]);
}
}
}
When recClubs is given to the user, all of the clubs are in one block of text and separated by commas. I want them to be separated by a line break. Any help is appreciated.
You could use join for array recClubs.push(clubs[h].join(', <br/>')); Actually you are adding array to innerHtml but it might be formatted string instead with <br/> tags
But data strucure should be :
var clubs=[["All In","Interact Club","Key Club"," Environmental Club"],[" Fall Production"," Spring Musical"], ["Student Government"],[" Tricorn"]].
or without changing data structure
function eliminateClubs(){
for(h=0;h<=personChoices.length;h++){
if (personChoices[h]==1){
var addedValue = Array.isArray(clubs[h]) ? clubs[h].join(', <br/>') :clubs[h] + '<br/>';
recClubs.push(addedValue);
}
}
Related
Hi all I am writing a function that will take in a string of names, then for each name if it is in a list, it will take the text of the name and add a link to it, if it is not it will simply display the text. The aim is to have these all in a single line when displayed.
function founderslinked(foundernames,foundersqueryname){
var foundernames=foundernames.split(", ");
var founderslinkstring='';
foundernames.map((foundername)=>{
var foundernamelower=foundername.toLowerCase();
var foundernamelower=foundernamelower.replace(/\s+/g, '-');
if(founderqueryname.indexOf(foundernamelower>=0)){
var thelink=`${links.index}/about/contributors/${foundernamelower}`;
var thelink=""+foundername+"";
var thelink.innerHTML=thelink;
founderslinkstring=founderslinkstring+","+thelink.
}else{
founderslinkstring+=founderslinkstring+" "+foundername;
}
})
return{founderslinkstring
}
}
founder names will be a string of the format "John Doe, Matt Jones, Frank Smith", and founderqueryname will be an array of the form ['john-doe','frank-smith].
The founderqueryname array is an array of the queries, of the people that have a personal page; if a query with their first and last name is in founderqueryname that means they have a personal page and it can be linked to.
I am essentially wanting to display all their names on a single line with this function. so I want to input the string of names and the array of queries. if there is a query with their name on it I want to add their name with a link to the single line we will display. if there is no query with their name I want to add only the text without a link to the line. using the above array and string, the function when called on the string and array
{founders linked(namesoffounders,queryoffounders);}
should display something like:
John Doe( text and link),Matt Jones(only text no link), Frank Smith(text and link)
"thelink" is essentially the pathway to the persons page if they have one and I am adding their name with a link to their page if they have a page. however this does not work. I am only getting the text as strings any ideas on what I am doing wrong?
Edit: as per #jaramanda x suggestion I got it to render by using the fixes he suggested I then ran:
{JSON.stringify(founderslinked(thelistoffounders,thelistoffounderqueries))}
however the above renders into text like this:
The names and text are displayed so are the proper links however, there is no, they do not show up as actual links any ideas?
I think this fixes ALL the issues in your code, and produces the expected output
Though I added a dummy links with an index property, since that is completely absent from your code
var links = {
index: 'xxx'
};
function founderslinked(foundernames, foundersqueryname) {
return {
founderslinkstring: foundernames.split(", ")
.map((foundername) => {
const foundernamelower = foundername.toLowerCase().replace(/\s+/g, '-');
if (foundersqueryname.includes(foundernamelower)) {
return `${foundername}`;
} else {
return foundername;
}
})
.join(',')
};
}
console.log(founderslinked("John Doe, Matt Jones, Frank Smith", ['john-doe', 'frank-smith']));
I have a simple script to generate a doc and PDF upon form submission. It worked well on simple template (e.g. Only 1 sentence, First name, Last name and Company name).
However, when I use a template that's longer, having many fields, and formatting, the code runs but replace the text randomly.
I have tried to hardcode the fields of forms in ascending order as the doc template. However it still replace the text randomly
Can anybody points out what have I done wrong?
My code:
function myFunction(e) {
var response = e.response;
var timestamp = response.getTimestamp();
var [companyName, country, totalEmployees,totalPctWomenEmployees,numberNationality,name1,position1,emailAdd1,linkedin1,funFact1,name2,position2,emailAdd2,linkedin2,gameStage,gameStory] = response.getItemResponses().map(function(f) {return f.getResponse()});
var file = DriveApp.getFileById('XXXXX');
var folder = DriveApp.getFolderById('XXXXX')
var copy = file.makeCopy(companyName + '_one pager', folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText('{{Company Name}}', companyName);
body.replaceText('{{Name}}', name1);
body.replaceText('{{Position}}', position1);
body.replaceText('{{Email}}', emailAdd1);
body.replaceText('{{Linkedin}}', linkedin1);
body.replaceText('{{Fun Fact}}', funFact1);
body.replaceText('{{Game Stage}}', gameStage);
body.replaceText('{{Game Story}}', gameStory);
doc.saveAndClose();
folder.createFile(doc.getAs("application/pdf"));}
My template -
Result -
Question - Does that mean the array declaration in line 3 was supposed to match the order of my form responses columns?
You can use Regular Expresion:
body.replace(/{{Company Name}}/g, companyName); // /g replace globaly all value like {{Company Name}}
Finally I found what have went wrong after so many trials and errors!
The reason is because I declared the array variables randomly without following the order of the form responses columns.
The issue is with the part -
var [companyName, country, totalEmployees,totalPctWomenEmployees,numberNationality,name1,position1,emailAdd1,linkedin1,funFact1,name2,position2,emailAdd2,linkedin2,gameStage,gameStory] = response.getItemResponses().map(function(f) {return f.getResponse()});
It's actually pulling responses from the spreadsheet, and should be corrected in order. The wrongly mapped values was what causing the replacement of text went haywire. I corrected the order as per form responses and it is all good now.
Learning points:
If you swapped around the variables, what response.getItemResponses().map(function(f) {return f.getResponse()} does is that it will go through the form responses column by column in order, and it will map the content to the wrong variable. As a result, when you replace your text later using body.replaceText('{{Game Stage}}', gameStage), there might be possibility that whatever stored in gameStage might be name1. Hence the replaced text will be wrong. And you will scratch your head until it bleeds without knowing why.
I saw #Tanaike's comment after I found the answer, but totally spot on!
Hi I am new to java script and i need help with the logic of the code. I have a list which is read from csv. Now if in the csv Others is in the middle so it appears in the middle. I want that if others exist in the list it should be added in the end. $scope.disconnectRequestReason is the array I am dealing with. $scope.disconnectRequestParameters[i].paramLabel can have the value other.
if($scope.disconnectRequestParameters[i].paramName == 'disconnectReason'){
$scope.disconnectRequestReason[countReason] = $scope.disconnectRequestParameters[i].paramLabel;
countReason++;
}
You could use length($scope.disconnectRequestReason[]) to get the size of the array and use length-1 to assign values to the last element. If there are multiple "others" you would need to keep count of assignments. In this case you would use length - othersCount and increment othersCount accordingly.
Your code would more or less look like this
if($scope.disconnectRequestParameters[i].paramName == 'disconnectReason'){
if($scope.disconnectRequestParameters[i].paramLabel == Others){
$scope.disconnectRequestReason[length - othersCount] = $scope.disconnectRequestParameters[i].paramLabel;
othersCount++;
} else{
$scope.disconnectRequestReason[countReason] = $scope.disconnectRequestParameters[i].paramLabel;
countReason++
}
So lets say I have a mailto email in which a checkbox question exists that asks the user to pick the best fruits out of a list of fruits (check all that apply.) They end up with apples, bananas, and pears. The mailto email that they trigger then contains the following (assuming the checkboxes in the question are named bestFruits):
...
bestFruits=apples
bestFruits=bananas
bestFruits=pears
...
So in my javascript file, I have the following line to parse values from the email:
var bestFruits = mail.bodyText.match(/bestFruits=\s*(\S.*\S)\s*/);
So my issue is that this would (presumably) take only one value by the end. What I need, is for the javascript to loop and add each value of bestFruits in the email to the bestFruits var so that each value (apples, bananas, and pears) are all in the bestFruits var.
Is there any way to do this? I tried making a for loop, but I couldn't determine the syntax to loop through the mailto email body and add each instance of bestFruits to the variable.
I'm still extremely new to all this, as I was thrust in recently. If I'm missing something fundamental, I'd appreciate a quick pointing-out. If you require any more info, I'd be happy to try to provide it.
Thanks for reading guys!
You don't need looping. You do need to match all the fruits (as per your example, matching all single words after bestFruits), remove bestFruits= from the matches, join the resulting array and store it in a variable. Like this:
var bestFruits = mail.bodyText.match(/bestFruits=\w+/g)
.map(function(x){return x.split('=')[1]})
.join(',');
What does it do:
Matches all your best fruits.
Takes each bestFruits=abc element and replaces it with abc (i.e., splits with = separator and takes the second part)
Makes the string of your fruits (converts the resulting array to string with , joiner).
You were very close - modified your regex a little bit:
var body = `this=is
an=example
bestFruits=apples
bestFruits=bananas
bestFruits=pears
of=doing
things=ok?
`;
var re = /bestFruits=(.*)/g;
var fruitMatches = body.match(re);
var bestFruits = fruitMatches.map(function(fruitMatch) {
return fruitMatch.split('=')[1];
});
console.log(bestFruits); // ["apples", "bananas", "pears"]
Fiddle
I'm trying to do something very simple, but I can't get to work the way I intend. I'm sure it's doing exactly what I'm asking it to do, but I'm failing to understand the syntax.
Part 1:
In the following example, I want to extract the part of the string between geotech and Input.
x = "geotechCITYInput"
x.match(/^geotech(.*)(?:Input|List)$/)
The result:
["geotechCITYInput", "CITY"]
I've been writing regex for many years in perl/python and even javascript, but I've never seen the ?: syntax, which, I think, is what I'm supposed to use here.
Part 2:
The higher level problem I'm trying to solve is more complicated. I have a form with many elements defined as either geotechXXXXInput or geotechXXXXList. I want to create an array of XXXX values, but only if the name ends with Input.
Example form definition:
obj0.name = "geotechCITYInput"
obj1.name = "geotechCITYList"
obj2.name = "geotechSTATEInput"
obj3.name = "geotechSTATEList"
I ultimately want an array like this:
["CITY","STATE"]
I can iterate over the form objects easily with an API call, but I can't figure out how to write the regex to match the ones I want. This is what I have right now, but it doesn't work.
geotechForm.forEachItem(function(name) {
if(name.match(/Input$/)
inputFieldNames.push( name.match(/^geotech(.*)Input$/) );
});
Any suggestions would be greatly appreciated.
You were missing the Input and List suffix in your regex. This will match if the name starts with geotech and ends with either Input or List and it will return an array with the text in the middle as the second item in the array.
geotechForm.forEachItem(function (name) {
var match = name.match(/^geotech(.*)(Input|List)$/);
if (match) {
inputFieldNames.push(match[1]);
}
});