Create javascript string with conditional and non conditional variables - javascript

I'm creating a single string using some defined variables like so:
var name = 'John';
var business = 'Google';
var email = name + ' registered the business ' + business;
In reality this is from a form submission so the variables will be set in a form and sent to my NodeJS backend to create this string. The user may or may not enter a message. I've created an if statement to add it to the string if they have:
if (message) email += '<br /><br />Message: ' + message;
The problem is when I expand this logic, it can get very messy. For example if I want to add several conditional variables to various points in the middle of the original string. Is there a way to do the conditional logic inside the initial string build?

Use a ternary operator. It can still get messy, but it reduces "if" everywhere.
var email = name + ' registered ' + business
+ (message ? '<br /><br />Message: ' : '') // conditional line
+ more_stuff...;

There are many ways you could structure the code to clean things up. A simple solution would be creating an object that keeps track of your various inputs, and then you could loop through that object to append all necessary items.
For example:
var obj = {
message: messageField,
messageTwo: messageTwoField
}
for (keys in obj){
if (key == message && obj.key) {
//append the string to a specific place
}
}
There are many ways to potentially solve this, but by storing everything in one object that can help to clean things up. Also, the if statement is conditional based on the key name and if there is a value assigned to that key name. This of course is just my opinion on how you could approach this, the size and complexity of the app could greatly change this answer.

Related

Is there any way to create space for a variable name within the var declaration in JavaScript?

I don't work with JavaScript, but I'm trying to find this answer. We want to change the _ within variable names into space. I know JavaScript does not allow this, but is there a clever way of doing this like concatenating the two into one such as:
var firstname + ' ' + lastname
Then put
firstname lastname = "Jack Jill";
Or perhaps some library calls. I know the above does not work because of + and '
You could do something as follows:
var firstName = "Jack";
var lastName = "Jill";
var fullName = firstName + " " + lastName;
console.log(fullName);
Spaces themselves are not a valid character for variable names, you should use underscores instead.
If you are looking to add a space between some variables you can do it by combining variables as shown below:
//Declare 2 variables
var firstName = 'kev';
var lastName = 'buntu';
//Declare variable to combine the two and add a space
var fullName = firstName + ' ' + lastName;
//Print the combined variable to verify the result
//should display "kev buntu"
console.log(fullName)
edit: given the OP's answers in comments it appears that this may be an XY problem, so potentially the solution is just creating a set of display text variables rather than directly using internal variable names as display values.
To strictly answer your question, 'no', there is no way to make a variable name with a space in it. This is not valid javascript.
You can make an object key with a space in it, by wrapping it in quotes, but I would avoid that if possible, and I don't think that's what you want anyway.
let obj = {
"firstname lastname": "John Doe"
}
You should stick with camel_case or snakeCase and furthermore, your variable names shouldn't be surfaced to the user (or client), so this shouldn't really matter.
As you need variable name to be spaced not value.
You can add it to context e.g.
context is window/this/xyz
window[firstname+' '+lastname] = "Jack Jill";
this[firstname+' '+lastname] = "Jack Jill";
xyz[firstname+' '+lastname] = "Jack Jill";
But while consuming it you have to use in similar(above) faison you can't use them directly as you can consume other variables.
For sure that's possible:
Using other whitespace than space, here U+3164
let firstNameļ¾ secondName = "You See";
console.log(firstNameļ¾ secondName);
There are multiple whitespaces in Unicode, just one of them is used by JS to separate identifiers. But please, don't do this.

How to make client side script variable dynamic within a repeat

I am trying to output som script using SSJS from a computedField like so:
var outScript = "<script>var data = " + datad.toString() + ";</script>"
The problem I have is that the computedField is within a doccollection repeat so I need to make the variable dynamic because I later need to access only the variable from the current entry using client side javascript (also within repeat)
How do I write to make the "data" variable dynamic within my repeat?
I know can create the variable using noteid or index, but I need to know how to write to output the variable i.e data1, data2 etc.
Hope you understand, a bit complicated to explain.
problably an easy answer I havn't thought of
thanks
Thomas
You could use the repeat's indexVar to save the data with a distinct key for each repeat entry:
var outScript = "<script>window.data_myRepeat_" + iRepeat.toFixed(0) + " = " + datad.toString() + ";</script>"
Here, it is assumed that the repeat's ID is "myRepeat" and indexVar is "iRepeat".

Creating and populating a json object

I need to construct and populate a json object with values coming from a method.
A bit of background to this: I'm searching pdf documents with a designated keyword and if I find any match, for each match I need to save:
-the whole sentence where the match is found
-the search term (defined elsewhere: the search term is always the same, so it's really redundant here, but I might need it in the json object that's why I'm including it)
-the result (which is the index where the search term is found in a whole sentence and it should be an integer)
So, here is some code.
I have this function call inside a loop (the loops goes through the pages and then there is a second loop that goes through the text):
for(var i = 0; i < items.length; i++){
lineWithResult = searchPdf(block.str);
if(lineWithResult != null){
console.log(lineWithResult + " wordCounter is " + wordCounter);
}
}
and the function itself:
function searchPdf(toSearch){
var result = toSearch.toLowerCase().indexOf(searchTerm);
if(result >=0){//if match is found
wordCounter++;
//console.log("toSearch " + toSearch + " result is " + result + " wordCounter " + wordCounter);
return toSearch;
}
else{//if match not found
return null;
}
}
SO I need to construct a json object that at each iteration takes in the parameters discussed above:
So, what would be the best way - I'm a bit rusty with json?
I think I would start by creating an empty object like so (if that's even a valid definition):
var searchResult = {"Line" : "", "SearchTerm" : "", "Result" : ""}
If the above is right, where do I define the object and how do I fill it up with the relevant values? Bear in mind that there will be a lot of Lines, one search term and a lot of Results because the documents (a pdf) which I will use are quite big and can returns lots of matches
thanks
With saying something like that:
var searchResult = {"Line" : "", "SearchTerm" : "", "Result" : ""}
You have already defined the object. JavaScript (at this point) is prototypical, not a "class" based language. JSON in JavaScript is not much more than just a plain JavaScript object. If you want to to create multiple objects of that kind, you have various options. I recommend you to read about JS Object creational patterns.
Here is a good link.
That being said, you could do something like that:
// ... maybe inside a function
return {
line: myLineValue,
searchTerm: mySearchtermValue,
result: myResult
}
There is no need to init something with empty values; you just create the object with the curly brackets.
Hope this makes sense to you; if not, let me know in the comments, and I will try to improve my answer. :-)

Adding and Displaying Array Issue

var reset = function ()
{
var p = parseFloat($("#IA").val());
var q = parseFloat($("#IB").val());
var m = parseFloat($("#CGCD").val());
var aR = [];
aR += ["GCD(" + p + "," + q + ")=" + m];
document.getElementById("PGCD").innerHTML = aR + "\n";
document.getElementById("IA-error").innerHTML="";
document.getElementById("IB-error").innerHTML="";
$("#IA").focus();
};
The code above is only for a 'reset' function, a part of additional code (not present), the purpose which is to find the Greatest Common Denominator, GCD.
My 'reset' function is connected to a button, #reset, the purpose of which is to do four things:
add and store the string GCD(p,q)=m to the array 'aR'; p/q/m are variable stand-ins for the values of the input text areas #IA, #IB, and #CGCD (the GCD of #IA and #IB);
display the array 'aR' in a text-area #PGCD each time the reset button is clicked; this is why I used an array;
clear the two input text areas #IA and #IB;
clear the one output text area;
As it stands, all four objectives are completed successfully, with one exception: for the second objective, only the most recent GCD calculation is outputted; none of the previous calculations output.
I cannot get the array to list the different saved calculations within it. I think (?) the new calculations are being added to the array, but I am not sure.
I've tried a 'for' statement, and an 'if' statement, neither of which worked. I don't know whether I coded it wrong, or if it wasn't the right solution for my issue.
I tried to search the forums (here) for a solution, but was unable to find one.
Thank you.
If I'm understanding what you are describing, I believe your problem is that you are attempting to use += to add elements to an array. You should use
aR.push("GCD(" + p + "," + q + ")=" + m);
The += operator is used for addition of a value to itself as well as string concatenation.
Edit: per comments below, the main issue was declaration of aR as a local variable. It needs to be either global or declared within the same scope.

Is there anyway to verify a google spreadsheets ID's

So don't crucify me too badly if this is a dumb question,
But I've been dabbling in Google App Scripts, mainly its uses within Google sheets.
Generally when I've been using openById()
If it's an ID that might change regularly, I'll put it at the top of my script and add notes on how to edit (for the user i hand sheet over to, or for me as a reminder if i've not worked on it for a bit and i forget). If's pretty stangnant and not likely to change, I'll just declare it as a var.
I was thinking it's a bit more user friendly to have a "settings" sheet within the spreadsheet and the user inputs the settings. Rather than having to go into script editor to edit things.
But even via sheet, or script editor, a single thing added or removed in the wrong place can cause havock, like a space or /
At least with a "settings" sheet, you can use data validation and regular expressions to control and reject what the user inputs.
So I guess my question is Google Sheets ID's seem alien to me, bar length, and I was wondering is there any way to validate the ID's using regular expressions or something, rather than checking the ID server side.
Thanks :)
You can also use openByUrl() in your scripts, so users can just paste a link.
but if you must validate the ID:
ss = SpreadsheetApp.getActiveSpreadsheet();
function validate(){
//"sheetRef" is the name of the cell where you enter the id
//this function takes the string value of "sheetRef"
//and replaces it with the validation result.
var sheetRefCell = ss.getRangeByName("sheetRef");
var sheetRefString = sheetRefCell.getValue();
var validationResult = '{' + sheetRefString + '}';
try {
validationResult = validationResult +
' \n $ references: \n [' +
SpreadsheetApp.openById(sheetRefString).getName() +
']';
}
catch (e) {
validationResult = validationResult +
' \n $ is an invalid reference: \n [' +
e +
']';
}
finally {
sheetRefCell.setValue(validationResult);
}
}
when you run this it will replace the value entered in your 'sheetRef' (ID) cell with the validation result message. I recommend that you also add a time-based trigger to contininuously revalidate your ID.
Then you can add another cell to your spreadsheet which will extract the validated ID from 'sheetRef'. This cell should contain the formula:
= IF (IFERROR( SEARCH( 'invalid' , sheetRef ), 0 ) > 0,
"Invalid",
IFERROR( REGEXEXTRACT( sheetRef,"{(.*?)}" ), "Undetermined" )
)
So the cell with the above formula will EITHER display a valid id or "Invalid"/"Undetermined".

Categories