I created a small function that stores the book isbn, it's name and it's author. Everything is fine until I start to print out array. On every entery that completes the object into array, I want it to be printed one after another in new row, but this one is printing the objects from beginning every time when a new object is inserted. How do I fix this?
var books = [];
function blaBla(){
while(isbn != null || name != null || writer != null){
var isbn = window.prompt("Enter ISBN");
var name = window.prompt("Enter name of the book");
var writer = window.prompt("Enter name of the writer");
var patternString = /^[a-zA-Z]+$/;
var patternNum = /^[0-9]+$/;
if(isbn.match(patternNum)){
if(name.match(patternString)){
if(writer.match(patternString)){
books.push({
isbn: isbn,
name: name,
writer: writer
});
}
}
}
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].name + " - " + books[i].writer + "</br>");
}
}
}
PS: How do I make it even more "cleaner", so when I hit cancel on prompt, it automatically stops with entering data into array, while, if i stop it on the "writer" prompt, it deletes previous entries for that object (last isbn and last name of the book)?
Thanks in advance.
You might want to give a little more context as to what this function is doing so we can help make your code cleaner as requested. I've separated the collection logic from the display logic here, and also used a while (true) loop with breaks on null or invalid inputs which will stop the collection of data.
Please note that prompt/alert boxes are a hideous way of collecting user input though (very awkward user experience). Consider using a table, input fields, and some jQuery instead to add rows and validate what the user has entered into input boxes.
var books = [];
function collectResponses() {
var patternString = /^[a-zA-Z]+$/;
var patternNum = /^[0-9]+$/;
while (true) {
var isbn = window.prompt("Enter ISBN");
if (!isbn || !isbn.match(patternNum)) {
break;
}
var name = window.prompt("Enter name of the book");
if (!name || !name.match(patternNum)) {
break;
}
var writer = window.prompt("Enter name of the writer");
if (!writer || !writer.match(patternNum)) {
break;
}
books.push({
isbn: isbn,
name: name,
writer: writer
});
}
}
function displayResponses() {
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].name + " - " + books[i].writer + "</br>");
}
}
Related
i am working on google apps script and i have come across an error which i cannot resolve.
the error occurs at the end on this line return ContentService.createTextOutput("thankyou...
I can't figure out the error. please assist me.
below is the full code
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1CIdq1anGwzUrfrNNd08NtgTR-QeHUDHgb4HOlnobmkk/edit#gid=0");
var sheet = ss.getSheetByName("Examiners");
function doGet(e){
var action = e.parameter.action;
if(action == "in")
return verified(e);
}
function doPost(e){
var action = e.parameter.action;
if(action == "in")
return verified(e);
}
function verified(e){
var id = e.parameter.id;
var values = sheet.getRange(2,1,sheet.getLastRow(),1).getValues();
for(var i = 0 ; i<values.length ; i++){
if(values[i][0] == id){
i=i+2;
var verified = Utilities.formatDate(new Date(), "EAT", "HH:mm:ss");
sheet.getRange(i,3).setValue(verified);
var fullname = sheet.getRange(i,2).getValue();
return ContentService.createTextOutput("Thank You" (fullname)"is verified at" (verified)).setMimeType(ContentService.MimeType.TEXT);
}
}
}
return ContentService.createTextOutput("Id Not Found").setMimeType(ContentService.MimeType.TEXT);
}
There were a few errors in your styling, one was how you concated strings. You used: "Thank You" (fullname)"is verified at" (verified), however this is a syntax error, as you need a + to conact several variables/strings to a string or use a template string, you got two options:
Using +: "Thank You " + fullname + " is verified at " + verified
Using template strings (Note: those are not done in quotation marks but in backticks): `Thank You ${fullname} is verified at ${verified}`
This is what I think how you mean, but I'm unsure about the last return as it was placed outside any function, I just but it one line up in the last function:
var sheet = ss.getSheetByName("Examiners");
function doGet(e) {
var action = e.parameter.action;
if (action == "in")
return verified(e);
}
function doPost(e) {
var action = e.parameter.action;
if (action == "in")
return verified(e);
}
function verified(e) {
var id = e.parameter.id;
var values = sheet.getRange(2, 1, sheet.getLastRow(), 1).getValues();
for (var i = 0; i < values.length; i++) {
if (values[i][0] == id) {
i = i + 2;
var verified = Utilities.formatDate(new Date(), "EAT", "HH:mm:ss");
sheet.getRange(i, 3).setValue(verified);
var fullname = sheet.getRange(i, 2).getValue();
return ContentService.createTextOutput("Thank You" + fullname + "is verified at" + verified).setMimeType(ContentService.MimeType.TEXT);
}
}
return ContentService.createTextOutput("Id Not Found").setMimeType(ContentService.MimeType.TEXT);
}
Furthermore I suggest you format your code better. Do you use an Editor? Many Editors can auto-format you your code, which makes it much more readable
Replace
return ContentService.createTextOutput("Thank You" (fullname)"is verified at" (verified)).setMimeType(ContentService.MimeType.TEXT);
by
return ContentService.createTextOutput("Thank You" + fullname + "is verified at" + verified ).setMimeType(ContentService.MimeType.TEXT);
Resources
Handling text — strings in JavaScript
Explanation. I am new to VueJS and JavaScript and I am trying to setup a search bar. So far, it works well, but I have one issue with it. I would like to be able to search through a description of an object even if the words I typed in the search bar are not in the correct order.
Example.
The string in the description would be "Gucci blue belt". If I type "Gucci blue", the result shows up since the description contains those words in this exact order. Therefore, I would like to add the functionality for which I can type "Gucci belt" and the item with the description "Gucci blue belt" would show up.
My current code in the computed section in VueJS
filteredsortedobjects (){
return this.sortedobjects.filter(object => {
var Objectslist_n = object.name;
var Objectslist_q = object.quantity;
var Objectslist_c = object.category;
var Objectslist_s = object.section;
var Objectslist_d = object.description;
var Objectslist_date = object.reception_date;
var Input = this.searchQuery;
/* Form arrays with all the information in the table */
var Objectslist_nq = Objectslist_n.concat(Objectslist_q);
var Objectslist_nqc = Objectslist_nq.concat(Objectslist_c);
var Objectslist_nqcs = Objectslist_nqc.concat(Objectslist_s);
var Objectslist_nqcsd = Objectslist_nqcs.concat(Objectslist_d);
var Objectslist_nqcsddate = Objectslist_nqcsd.concat(Objectslist_date);
/* Filtered variables */
var F_Objectslist = RemoveAccents(Objectslist_nqcsddate.toLowerCase());
var F_Input = RemoveAccents(this.searchQuery.toLowerCase());
/* Function to remove accents */
function RemoveAccents(str) {
var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
str = str.split('');
var strLen = str.length;
var i, x;
for (i = 0; i < strLen; i++) {
if ((x = accents.indexOf(str[i])) != -1) {
str[i] = accentsOut[x];
}
}
return str.join('');
};
console.log(F_Objectslist);
console.log(F_Input);
return F_Objectslist.includes(F_Input)
})
}
I am aware that the function to remove accents is not yet used since I have been testing things.
What I have tried doing. I have tried setting the variable F_Input (what is being written in the search bar) and F_Objectslist (a variable containing an array with all the words for the items, for instance, the names, the category, the section, the quantity, a description and a date) as strings by array.split(" "). That way, I was able to have an array of strings in this format in the console ["word", "word2", ...] for both my variables.
From this point, I am unsure on how to check if the strings in my F_Input array are all present in the array for F_Objectslist even if they are in a different order.
Thank you so much for your time!
Split F_Input on " ", then you can use 'Array.prototype.map()' to loop through the F_Input array of search terms using the same technique you have now.
Notice that I've chained all these together with a final call to the .every() method. That last one says that every map operation (search) must result in a true (or the result of the map operation must result in an array full of nothing but true);
const F_Objectslist = "this is search term, and this is term search".split(' ');
const F_Input = "search term";
let result = search(F_Objectslist, F_Input);
console.log(result);
let notFoundResult = search(F_Objectslist, "search dog");
console.log(notFoundResult);
function search(text, terms) {
return terms.split(' ').map(term =>text.includes(term)).every(found=>found===true);
}
I think you were already pretty close, I would approach it like this
function searchString(input, match) {
let is_a_match = true;
const match_arr = match.split(' ');
const input_arr = input.split(' ');
input_arr.forEach(word => {
if (match_arr.indexOf(word) === -1) {
is_a_match = false;
}
});
return is_a_match;
}
A working fiddle can be found here
Here is my answer.
I managed to make a quite responsive search bar that seeks information in the array! Here is the code if anyone is curious about it!
page.vue inside computed
filteredsortedobjects (){
return this.sortedobjects.filter(object => {
var Objectslist_n = "a" + object.name;
var Objectslist_c = object.category;
var Objectslist_s = object.section;
var Objectslist_q = object.quantity;
var Objectslist_d = object.description;
var Objectslist_date = object.reception_date;
var Input = this.searchQuery;
/* Form arrays with all the information in the table */
var Objectslist_nc = Objectslist_n + " " + Objectslist_c;
var Objectslist_ncs = Objectslist_nc + " " + Objectslist_s;
var Objectslist_ncsq = Objectslist_ncs + " " + Objectslist_q;
var Objectslist_ncsqd = Objectslist_ncsq + " " + Objectslist_d;
var Objectslist_ncsqddate = Objectslist_ncsqd + " " + Objectslist_date;
/* Filtered variables */
var F_Objectslist = RemoveAccents(Objectslist_ncsqddate.toLowerCase()).split(" ") + " ";
var F_Input = RemoveAccents(this.searchQuery.toLowerCase()).split(" ");
/* Function to remove accents */
function RemoveAccents(str) {
var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
str = str.split('');
var strLen = str.length;
var i, x;
for (i = 0; i < strLen; i++) {
if ((x = accents.indexOf(str[i])) != -1) {
str[i] = accentsOut[x];
}
}
return str.join('');
};
return F_Input.every(object => {
if (F_Objectslist.indexOf(object) === -1) {
}
else {
return F_Objectslist.indexOf(object)
}
})
})
}
I have an input with a v-model="searchQuery" attribute. Also, there is a table containing
<tr id="tr" v-for="object in filteredsortedobjects" v-bind:key="object.name">
<td>
<p>{{ object.name }}</p>
</td>
<td>
<p>{{ object.category }}</p>
</td>
<td>
<p>{{ object.section }}</p>
</td>
<td>
<p>{{ object.quantity }}</p>
</td>
<td>
<p>{{ object.description }}</p>
</td>
<td>
<p>{{ object.reception_date }}</p>
</td>
</tr>
The object.something are imported from a JSON file using
<script>
import objects from "./Database/Objects.json";
</script>
You would probably have to set some data information in the data() section
searchQuery: ""
So I need to pull a number value from a string. I currently have a working solution but I feel that maybe I can improve this using a regular expression or something.
Here is my working solution
var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}
As you can see I'm trying to pull the number value from after the "[REF: " string.
// Change of the text for better test results
var subject = "hjavsdghvwh jgya 16162vjgahg451514vjgejd5555v fhgv f 262641hvgf 665115bs cj15551whfhwj511";
var regex = /\d+/g;
let number = subject.match( regex )
console.log(number)
It Will return array for now, and if no match found, it will return null.
For most of the time, when i used this regex i get perfect result unless if string contains decimal values.
var str = 'This is a test message [REF: 2323232]'
var res = str.match(/\[REF:\s?(\d+)\]/, str)
console.log(res[1])
If you don't want to use a regular expression (I tend to stay away from them, even though I know they are powerful), here is another way to do it:
// Your code:
/*var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}*/
// New code:
const subject = "This is a test message [REF: 2323232]";
const codeAsString = subject.split('[REF: ')[1]
.split(']')
.join('');
if (!isNaN(parseInt(codeAsString))) {
console.log('Valid ticket number: ', parseInt(codeAsString));
}
else {
console.log('Invalid ticket number: ', codeAsString);
}
This will extract number
var subject = "This is a test message [REF: 2323232]";
var onlyNum = subject.replace(/.*(:\s)(\d*)\]$/,'$2');
console.log(onlyNum)
Here, same but the number is now a real int
var subject = "This is a test message [REF: 2323232]";
var onlyNum = parseInt(subject.replace(/.*(:\s)(\d*)\]$/,'$2'));
console.log(onlyNum)
I created this javascript to auto populate a field, with values from other fields. It is called in the form onSave event.
function OppTopic() {
var products = "";
var parent = Xrm.Page.getAttribute("parentaccountid").getvalue();
var city = Xrm.Page.getAttribute("address1_city").getValue();
var automation = Xrm.Page.getAttribute("new_automationfeatures").getValue();
var service = Xrm.Page.getAttribute("new_service").getValue();
//Determines if a Product/Service is selected
if (automation == true) {//***AUTOMATION***
if (products != ""){
products += ",Automation";
}
else{
products = "Automation";
}
}
if (service == true) {//***SERVICE***
if (products != "")
products += ",Service";
else
products = "Service";
}
if (automation == false && service == false) {
products = "null";
}
var subject = parent + " - " + city + " - " + products;
Xrm.Page.getAttribute("name").setValue(subject);
}
But , when the form is saved this is the error that appears.I'm not really sure what the error means?
I have checked the field names and they are correct.
What could be the problem that is causing this error?
Thanks
var parent will return a javascript object that is a CRM lookup. If you are putting it together in a string with other strings, you will have to retrieve the name or whichever other attribute from the lookup you're trying to add
var parentName = "";
var parent = new Array();
parent = Xrm.Page.getAttribute("parentaccountid").getValue();
if(parent!=null){
parentName = parent[0].name;
}
Source: http://www.mscrmconsultant.com/2012/08/get-and-set-lookup-value-using.html
function Todo(id, task, who, dueDate) {
this.id = id;
this.task = task;
this.who = who;
this.dueDate = dueDate;
this.done = false;
}
// more code that adds the todo objects to the page and to the array todos
function search() {
for (var i = 0; i < todos.length; i++) {
var todoObj = todos[i];
console.log(todoObj.who); //shows both jane and scott
console.log(todoObj.task); // shows both do something and get milk
}
var searchTerm = document.getElementById("search").value;
searchTerm = searchTerm.trim();
var re = new RegExp(searchTerm, "ig");
var results = todoObj.who.match(re);
if (searchTerm == null || searchTerm == "") {
alert("Please enter a string to search for");
return;
} else {
alert(results);
}
}
This is a search function where I am trying to match what the user types into the search bar with objects that I have created earlier in the code. They must match the "who" and "task" parameters that I have given to the objects. So one object is who: jane task: do something and the other is who: scott task: get milk. The problem is, in my last alert I can only match scott and not jane. Scott is the last one I added. Is there some way I need to modify my loop or change my search criteria?
Your problem is that you are looping through the items, but then using todoObj after that loop. So todoObj will just hold the last item in the array. You need to reorganize a little...try something like this:
function search() {
var searchTerm = document.getElementById("search").value;
searchTerm = searchTerm.trim();
if (searchTerm == null || searchTerm == "") {
alert("Please enter a string to search for");
return;
} else {
var todoObj = undefined,
results = undefined,
re = new RegExp(searchTerm, "ig");
for (var i = 0; i < todos.length; i++) {
todoObj = todos[i];
results = todoObj.who.match(re);
if (results) {
alert("You found " + todoObj.who + ", who needs to " + todoObj.task + " by " + todoObj.dueDate);
return;
}
console.log(re.lastIndex);
}
alert("You didn't match anyone");
}
}
Here's an example of it working as I think you want it to: http://jsfiddle.net/sHSdK/2/