Multiple search creteTextFinder app scrip [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm currently working on a project where I send data to a google sheet through app script.
I need to change the value of some data and used createTextFinder.
Thanks to #Mimi in this thread. But the fact is that I need to replace more than one text.
I need to change the text when the data is appending.
thanks in advance
Here is my code
function addUser(sheet) {
var FILE = SpreadsheetApp.openById("XXXXXXXXXXXXX");
var sheet = FILE.getSheetByName("Sheet1");
var id = "True";
var name = "FALSE";
var t1 = createTextFinder("TRUE").replaceAllWith("YES")
var t2 = createTextFinder("FALSE").replaceAllWith("NO")
sheet.appendRow([id,name]).t1.t2;

From I need to change the text when the data is appending., in this case, how about the following modification?
From:
var t1 = createTextFinder("TRUE").replaceAllWith("YES")
var t2 = createTextFinder("FALSE").replaceAllWith("NO")
sheet.appendRow([id,name]).t1.t2;
To:
var values = [id, name].map(e => {
var temp = e.toUpperCase();
return temp == "TRUE" ? "YES" : temp == "FALSE" ? "NO" : e;
});
sheet.appendRow(values);
For example, when you are required to use TextFinder, how about the following modification?
From
var t1 = createTextFinder("TRUE").replaceAllWith("YES")
var t2 = createTextFinder("FALSE").replaceAllWith("NO")
sheet.appendRow([id,name]).t1.t2;
To
sheet.appendRow([id, name]);
sheet.createTextFinder("TRUE").replaceAllWith("YES");
sheet.createTextFinder("FALSE").replaceAllWith("NO");
or, when you want to use TextFinder to the appended row, you can also the following modified script.
sheet.appendRow([id, name]);
// SpreadsheetApp.flush(); // This might be not required to be used.
const range = sheet.getRange(sheet.getLastRow(), 1, 1, 2);
range.createTextFinder("TRUE").replaceAllWith("YES");
range.createTextFinder("FALSE").replaceAllWith("NO");

Multiple Replacement
function addUser() {
const txtA = ['txt1', 'txt2', 'text3'];
const rplA = ['rpl1', 'rpl2', 'repl3'];
var ss = SpreadsheetApp.openById("XXXXXXXXXXXXX");
var sh = ss.getSheetByName("Sheet1");
txtA.forEach((t, i) => {
let f = sh.createTextFinder(t).findAll();
if (f) {
f.forEach(r => { r.setValue(r.getValue().replace(txtA[i], rplA[i])); });
}
});
}

Related

Attaching Dynamic Variable in ES6 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a problem attaching a dynamic variable when Im using find method in ES6. Pls check my code below. I need to attached the productValue. Is this not possible?
const productValue = 1;
products.find((item => item.option[productValue] === 'food'))
This is not correct usage of find in array. Look at the sample:
products = ["vegetable", "food", "test"];
const productValue = 1;
var res = products.find((item => console.log(item)));
Now look at this one:
products = ["vegetable", "food", "test"];
const productValue = 1;
var res = products.find((item => console.log(item[1])));
See you are using "vegetable"[1] that is first character of each string
You know the index so easily check in if products[productValue] == "food"; Or of you want find by index use findIndex.
Upadte
After chattin with OP I understand he wants to append the productValue to one of products key value (option that is string), so you need to use + operator:
products.find((item => (item.option + productValue) === 'food'))
You can use the index parameter to check whether a specific item in an array equals some value.
sample:
const productValue = 1;
const products = ['beverages', 'food'];
console.log(products.find((item, index) => index === productValue && item === 'food'));
const products = ["vegetable", "food", "test"];
const productValue = 1;
const updatedFruits = products.map(product => {
if(product === "food"){
return product + productValue
}
return product;
});
console.log(updatedFruits)

Changing function name with array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Could someone say how to make an array of function names that will change in while loop?
Example of what I want:
var funcNames = ['function1()', 'function2()', 'function3()','function4()','function5()'];
var i = 0;
while( i < funcNames.length ) {
function funcNames[i] {
alert("hello");
}
i++;
}
In the example, the code doesn't work. It only shows how the code should work.
You can think about create new dynamic function name in javascript? like below:
var funcNames = ['function1()', 'function2()', 'function3()','function4()','function5()'];
var i = 0;
var result = [];
while( i < funcNames.length ) {
var funcName = funcNames[i];
var func = new Function("return function " + funcName + "{ alert('hello')}");
result.push(func);
i++;
}
console.log(result);
var firstFunc = result[0]();
console.log(firstFunc()); // invoke one func here

How to add a cut string in the list with javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a small problem with the JavaScript. I would like to add the string (format:one-two-three) the list, but this cut the sign ("-") and every elements tag add. I try solve this problem, unfortunatelly don't succeeded. Here my function:
function listAdd(){
var string = document.forms["form1"].elements["stringAdd"].value;
if(string != ""){
var array = string.split("");
var eredmeny = array.some(function(v) { return v == "-";});
if(eredmeny){
for(var i = 0; i <array.length; i++){
if(array[i] != "-"){
var newElement = document.createElement('li');
array[i] = array.toString();
newElement.textContent = array[i];
var list = document.getElementById("gyumi");
list.appendChild(list.createTextNode(array[i]));
}
}
}
else{
var newElement = document.createElement('li');
newElement.textContent = szoveg;
var list = document.getElementById("gyumi");
list.appendChild(newElement);
}
}
}
Sorry, poor my English and this is the first question to me.
My assumption here is that you're trying to create li items from a string that is delimited by the '-' character. Should that be true, see the following:
You can split your string into it's subcomponents by the .split() function as you've used and then iterate over those elements and create the list items and append them to the body of the document.
var mystr = 'one-two-three';
var components = mystr.split('-');
components.forEach(function(comp){
var item = document.createElement('li');
item.textContent = comp;
// set your attrs on the item here
document.body.appendChild(item);
});
I think you're saying you have a string like "one-two-three" and you want to split that up on the - and add the resulting "one", "two", and "three" to the list.
If so, you want to use split("-") rather than split("") and you don't need the some to check for -. Also, you can use createTextNode to put in the list item content (textContent is not cross-browser compatible), and you only need to get the list once:
function listAdd() {
var string = document.forms["form1"].elements["stringAdd"].value;
if (string != "") {
var list = document.getElementById("gyumi");
string.split("-").forEach(function(entry) {
var newElement = document.createElement('li');
newElement.appendChild(document.createTextNode(entry));
list.appendChild(newElement);
});
}
}
listAdd();
<form name="form1">
<input type="text" name="stringAdd" value="one-two-three">
</form>
<ul id="gyumi"></ul>
That works even if there is no - in the string, because split("-") will return just a single element in the array if there are no - in the string.
You can do this with split, but it becomes a lot easier if you split by -. Then you have exactly the values you want to add to the list.
Secondly, if you run this function when the form is submitted, or on the click of a form button, make sure to cancel the form submission.
Finally, you will want to clear in the input when the items have been added to the list.
function listAdd() {
var inp = document.forms["form1"].elements["stringAdd"];
var list = document.getElementById("gyumi");
var string = inp.value;
if (string != "") {
string.split('-').forEach(function (item) { // split by the hyphen
var newElement = document.createElement('li');
newElement.textContent = item;
list.appendChild(newElement); // not a text node
});
}
// clear input once you have added the items:
inp.value = '';
return false; // cancel form submission
}
<form id="form1" onsubmit="return listAdd()">
Items: <input name="stringAdd"> [Press enter to add]
</form>
<ul id="gyumi"></ul>

How to get variable from different function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
So what I'm trying to do is get a search term from one function getRandomVideo() and use it in a jQuery statement, so for example, get beethoven from the variable searches and use it as the search term to get back JSON information and append it to a div. I know next to nothing about jQuery so any help would be great thanks :)
<script type="text/javascript">
function getRandomVideo() {
var videos = [
'https://www.youtube.com/embed/kiTO7c_qeZs',
'https://www.youtube.com/embed/z4Hfv00eqoI',
'https://www.youtube.com/embed/7cdZYQB5ONE',
'https://www.youtube.com/embed/i1gE3nyQnKg',
];
var titles = [
'Beethoven - Music, Love and Wine',
'Mozart String Serenade No.13',
'Beethoven Sonata No. 31 in A Flat Major',
"Debussy - Children's Corner",
];
var images = [
"url('Assets/beethoven.jpg')",
"url('Assets/mozart.jpg')",
"url('Assets/beethoven.jpg')",
"url('Assets/debussy.jpg')",
]
var searches = [
'beethoven',
'mozart',
'beethoven',
'debussy',
]
var rand = Math.floor(Math.random()*videos.length);
var video = videos[rand];
var title = titles[rand];
var image = images[rand];
var search = searches[rand];
document.getElementById("songTitle").innerHTML = title;
document.getElementById("img").style.backgroundImage = image;
var htmlVideo = document.getElementById("randomVideo");
htmlVideo.src = video;
htmlVideo.onload=null;
return search
}
getRandomVideo();
$(document).ready(function(){
// Im not sure what to do here to get it to run when the page starts
// Get the value from our getRandomVideo()
var searchTerm = getRandomVideo();
var url = "http://api.trove.nla.gov.au/result?key=jja10ssv4950uh65&encoding=json&zone=newspaper&sortby=relevance&q=" + searchTerm + "&s=0&n=5&include=articletext,pdf&encoding=json&callback=?";
/*
* Perform the search using jQuery's getJSON method
* Requires the search URL
*/
console.log(url);
$.getJSON(url, function(data) {
$.each(data.response.zone[0].records.article, function(index, value) {
$("#output").append("<p>" + value.articleText +"</p>");
});
});
};
</script>
This should give you an idea as to how to accomplish this...
var getRandomVideo = (function(){
var _videos = [
'https://www.youtube.com/embed/kiTO7c_qeZs',
'https://www.youtube.com/embed/z4Hfv00eqoI',
'https://www.youtube.com/embed/7cdZYQB5ONE',
'https://www.youtube.com/embed/i1gE3nyQnKg',
];
var _titles = [
'Beethoven - Music, Love and Wine',
'Mozart String Serenade No.13',
'Beethoven Sonata No. 31 in A Flat Major',
"Debussy - Children's Corner",
];
var _images = [
"url('Assets/beethoven.jpg')",
"url('Assets/mozart.jpg')",
"url('Assets/beethoven.jpg')",
"url('Assets/debussy.jpg')",
];
var _searches = [
'beethoven',
'mozart',
'beethoven',
'debussy',
];
return {
videos: function(){ return _videos; },
titles: function(){ return _titles; },
images: function(){ return _images; },
searches: function(){ return _searches; }
};
})(); // this is the module pattern FYI
var rand = Math.floor(Math.random() * getRandomVideo.videos().length);
var video = getRandomVideo.videos()[rand];
var title = getRandomVideo.titles()[rand];
var image = getRandomVideo.images()[rand];
var search = getRandomVideo.searches()[rand];
document.getElementById("songTitle").innerHTML = title;
document.getElementById("img").style.backgroundImage = image;
var htmlVideo = document.getElementById("randomVideo");
In javascript, everything including variables are scoped by function so any variable declared inside a function such as...
function myFunction()
{
var a1 = "something";
}
var test = a1; // a1 would be undefined as it is out of scope of `myFunction()` so test would be too of course
By using the module pattern, you can expose properties/functions within the return{}; statement. NB: the underscores are just to identify private functions/objects etc ;)
Also if you were to do the below, you would be able to access a1 as it would cascade into global scope as it has not been declared...
function myFunction()
{
a1 = "something";
}
var test = a1; // a1 would be "something"
But I wouldn't suggest this... for a number of architectural reasons :-/

how to sort the object array to map with respect to fields in object array using java script [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an object array like this
[
{bookName:"javascript",authorName:"john"},
{bookName:"java",authorName:"peter"},
{bookName:"j2ee",authorName:"john"},
{bookName:".net",authorName:"peter"},
{bookName:"oracle",authorName:"peter"}];
I tried the logics but i didnt get correctly.I want to sort out like this..
{
peter:{
[{bookName:"java",authorName:"peter"},
{bookName:".net",authorName:"peter"},
{bookName:"oracle",authorName:"peter"} ]
} ,
john :{
[{bookName:"j2ee",authorName:"john"},
{bookName:"javascript",authorName:"john"}]
}
}.
how can i do that.. Thanks in Advance ..
var obj={};
var objArr = given objectarray;
for(var i=0;i<objArr.length.i++ ){
objArr[objArr[i].authorName]=objArr[i];
}
and
var obj={};
var objArr = given objectarray;
for(var i=0;i<objArr.length.i++ ){
var arr=[];
objArr[objArr[i].authorName]=arr.push(objArr[i]);
}
You could do this:
var b = ... your object ...
var m = {};
b.map(function(v){(m[v.authorName]=m[v.authorName]||[]).push(v)});
Demonstration (open the console)
http://jsfiddle.net/azqRu/
var array = [
{bookName:"javascript",authorName:"john"},
{bookName:"java",authorName:"peter"},
{bookName:"j2ee",authorName:"john"},
{bookName:".net",authorName:"peter"},
{bookName:"oracle",authorName:"peter"}
];
var items = {};
for(var i = 0, ii = array.length; i < ii; i++) {
var cell = array[i];
items[cell.authorName] = items[cell.authorName] || [];
items[cell.authorName].push(cell);
}
alert(items["peter"]);

Categories

Resources