Concatenating Multiple String and Texts Together Into A String - Blogger Javascript - javascript

I have 2 questions here :
Question 1.
How to concatenate multiple text and strings into one String variable and return the string?
function TagGen()
{
var getTitle="Nidome no Jinsei wo Isekai de Chapter 1 Raw Manga";
var getTag=getTitle.substring(0, getTitle.lastIndexOf(" Chapter"));
var setTags={""+getTitle+", "+getTitle+" Raw Manga"+", "+getTitle+", "+getTag+" Raw Manga"+", "+getTag+" Raw"+", "+getTag+" Manga Download"+", "+getTag+" Download"+", "+getTag+" jcafe"+", "+getTag+" Chapter Download,"+", "+getTag+" Raw Chapters"+", "+getTag+" jcafe24"+", "+"Raw Download"+", "+getTitle+" Raw Manga Download"+", "+getTitle+" jcafe"};
return setTags;
}
I want the setTags to be have the string value something like the below,
I tried to run this code several times in Tryit Editor but didn't get setTags variable working. Please help.
Question 2.
I want to store multiple tags of my blogger blog post into one String.
I know that there must be some b:loop used but I still have not yet fully understood its uses.
Suppose I have a post with the labels : Action,Adventure,Romance,Shounen
I want it to get all those labels and store it in a String like:
labels=Action,Adventure,Romance,Shounen
The basic idea of the saving into String is same as the first question but I don't know how to get multiple tags and do it.
Please help :D

To get all the labels present in a post into a variable in a concatenated form, you can use the following code -
<script>
var labelArray = <b:eval expr='data:post.labels map (label => label.name)' />;
var labels = labelArray.join(',');
</script>
This utilizes the Lambda operator map provided by Blogger.

Related

How to use .contains() or any other function to see if any part of a string is in an array

I am trying to cut down and make my code simpler since my original method is not very readable and I get a lot of hard to understand errors for which I have to scan all of the code word by word as it is all one long line.
Lets say the text input was for
In my original code, I wrote :
//Example : You want to know if any of your favorite games were licensed by Nintendo
var tsf = (The value of a textInput in string form)
tsf.toLowerCase()
//Lets say the textinput said "Name your favorite games"
if(tsf.contains('mario') || tsf.contains('pokemon') || tsf.contains('mortal kombat')||etc,etc) {
Alert.alert('At least one of these games was licensed by Nintendo')
}
This works but in the real code there are a lot more "games" and it requires each and every item in the list as it is related to a health project I'm working on.
My 2nd idea was to create an array with all the elements and see if the array contains tsf
nintendoGames = ['mario','pokemon','mortal kombat','zelda','tetris',etc]
if(nintendoGames.contains(tsf)){
Alert.alert('This game was licensed by Nintendo')
}
This also works but only if tsf is a single word. Incase
tsf = 'mario, zelda'
the array method would not work since the array only contains 'mario' and 'zelda' and not the string 'mario, zelda'
I want to be able to scan to see if any part of the string contains any one of the elements in the array and so far, only the first solution works for me. If there is a modification in the .contains() function that works or if there is a certain script I have to write, it would be very useful. I wasn't able to find much online about this.
I am working on React.js with expo to host the app.
First, we convert the string to an array using 'split'.
Since we separate the games in the string with ', ' your code should be like:
tsf.split(', '); // we receive: ['mario','zelda'].
Then we use 'some' method to check if some of the elements in the array we created are in the 'nintedoGames' array.
const tsf = 'mario, zelda';
const nintendoGames = ['mario', 'pokemon', 'mortal kombat', 'zelda', 'tetris'];
const result = tsf.split(', ').some(game => nintendoGames.includes(game.toLowerCase()));
console.log(result)
let nintendoGames = ['mario','pokemon','mortal kombat','zelda','tetris'];
let str = "This is a mario games where you can play the way you like.";
if(nintendoGames.some(n => str.toLowerCase().includes(n.toLowerCase())))
alert("This game was licensed by Nintendo");

Form's App Script does not replace fields in template accurately

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!

Adding breaks in an array

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

making an array or choice field with a string separated with <br/>

I have a string:
Name1<br/>Name2<br/>Name3
Im looking to get a choice selector or an array with just the Names as values. I know you can get just the text of a string, but I cant figure out a way separate them. This list changes so I cant hard code the names in.
I cannot find any code nor do I have anything yet.
Use the split function:
var text = "Name1<br/>Name2<br/>Name3";
var list = text.split("<br/>");
This is easily accomplished using JavaScript built-in split().
var input_s = "Name1<br />Name2<br />Name3";
var input_r = input_s.split("<br />");

Parse response using Jquery

I have to parse a response from the server,
The response is like..
[4,"1.0",1368544417760]
[1,"Great West Road","222",1368544595000]
[1,"Ruislip Manor Station","114",1368544479000]
[1,"Bank Station / Threadneedle Street","26",1368544731000]
[1,"Belvue School","E10",1368545955000]
[1,"Brunel Road","283",1368544706000]
[1,"Annesley Avenue","303",1368545930000]
[1,"Brixton Station Road","35",1368545854000]
[1,"Southampton Row","91",1368545537000]
[1,"Camden Road Station","29",1368545008000]
[1,"Fulham Cemetery","74",1368545210000]
The response doesn't seem to like JSON or XML.
Please help me know how to parse such type of response using Jquery.
I have to update the DOM based on the response and the response is getting updated
at a regular interval automatically.
The first number may be an indicator of what sort of data is in the rest of the "array".
I'd say
parse each line as if it were JSON. It'll turn into a javascript array.
var array = JSON.parse(oneLine); // Many browsers support this.
Then pull the bits out and put them into a proper object by name. (How to do that depends on the 1st element, perhaps.)
var obj = {};
if (array[0] == 1) {
obj.station = obj[1];
obj.number = obj[2];
obj.timestamp = obj[3]; // guessing what this is, too.
}
Do whatever you need with the data object.
Put all that in a loop. Repeat until done.
There is a similar Stack Overflow question here --> converting CSV/XLS to JSON?
Looks like there are a few different possible solutions that you could look at.

Categories