Javascript: How do I append a string to Google search query? - javascript

I want to programmatically append +test1+test2+test3 to https://www.google.co.uk/?gws_rd=ssl#q=
Fiddler captured this web session:
I tried this code, but it's not working
if (oSession.uriContains("www.google.co.uk/?gws_rd=ssl#q="))
{
var str = oSession.fullUrl;
var sAppend = "+test1+test2+test3";
if (!oSession.uriContains(sAppend))
{
oSession.fullUrl = str + sAppend;
}
}
Thank you

Related

Line-breaks in between of text using JS ,(Dynamically)

I am stuck on a very beginner problem in JS, what I'm trying to do is add line-breaks in between text which the script adds dynamically after generating a random string, but I could not find a source that would match my case
The code that picks a random string
var textArray = [
'Gateway to wild imaginations!',
'Activating the send portal :D',
'Empowering nothing ;P'
];
var randomNumber = Math.floor(Math.random()*textArray.length);
var rndStr = textArray[randomNumber];
const h_1_elem = document.getElementById('main-h1');
h_1_elem.innerText = rndStr;
I would consider myself a beginner in programming so take this question with a pinch of salt
You could use \n to insert a new line since you are using
h_1_elem.innerText = rndStr + "\n";
Also I created a function called randomNumber in order to call it more than one time.
var textArray = [
'Gateway to wild imaginations!',
'Activating the send portal :D',
'Empowering nothing ;P'
];
const h_1_elem = document.getElementById('main-h1');
h_1_elem.innerText = textArray[randomNumber()] + "\n";
h_1_elem.innerText += textArray[randomNumber()] + "\n";
function randomNumber() {
let number = Math.floor(Math.random()*textArray.length);
return number;
}
<div id="main-h1"></div>
If you run the code multiple times, you will get different messages. Just keep adding more :)
Regards
============ EDITED ============
Oh, you want a break line after each word. Didn't understand the question that way. So, for that you should use something like this:
var textArray = [
'Gateway to wild imaginations!',
'Activating the send portal :D',
'Empowering nothing ;P'
];
const h_1_elem = document.getElementById('main-h1');
h_1_elem.innerText = textArray[randomNumber()].replaceAll(" ","\n");
function randomNumber() {
let number = Math.floor(Math.random()*textArray.length);
return number;
}
<div id="main-h1"></div>
I just used
replaceAll(" ", "\n")
In order to replace every space by a break line. Hope this is what you want.
Regards
Don't use .innerText and instead use .innerHTML along with the HTML line break element of <br>:
var textArray = [
'Gateway to wild imaginations!',
'Activating the send portal :D',
'Empowering nothing ;P'
];
var rndStr = textArray[Math.floor(Math.random()*textArray.length)];
const h_1_elem = document.getElementById('main-h1');
h_1_elem.innerHTML = rndStr + "<br>";
rndStr = textArray[Math.floor(Math.random()*textArray.length)];
h_1_elem.innerHTML += rndStr + "<br>";
<div id="main-h1"></div>

How to split JSON data from app script on a spreadsheet getting info from Wialon platform

I've collected some code to get this work, this GPS platform (Wialon) is for tracking vehicles and it has some functions to get notifications, one of them is to send them via server GET / POST method, so I have the following result in one cell:
{"|2020/08/13 18:57|CR-03 FR|0 km|🦂|JESUS SALVADOR GARCIA SCOTT|":""} //example
I separated some values by "||||" characters just to split them easily by SPLIT() formula in Google Sheets, but I want a cleaner result from the script, this is what I got from this code:
Please if you can help me to get this FINAL result, it didn't have to be necessarily formatted (date), this already splitted and separated by "|":
In this code are other functions that send the same data to a Telegram Group, ignore it, just put it here in case helps to anyone.
var token = "FILL IN YOUR OWN TOKEN"; // 1. FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = "FILL IN YOUR GOOGLE WEB APP ADDRESS"; // 2. FILL IN YOUR GOOGLE WEB APP ADDRESS
var ssId = "FILL IN THE ID OF YOUR SPREADSHEET"; // 3. FILL IN THE ID OF YOUR SPREADSHEET
var adminID = "-XXXXXXXXX"; // 4. Fill in your own Telegram ID for debugging
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + encodeURIComponent(text);
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e) {
try {
// this is where telegram works
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var name = data.message.chat.first_name + " " + data.message.chat.last_name;
var answer = "Hi " + name;
sendText(id,answer);
SpreadsheetApp.openById(ssId).getSheets()[0].appendRow([new Date(),id,name,text,answer]);
if(/^#/.test(text)) {
var sheetName = text.slice(1).split(" ")[0];
var sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheetName) ? SpreadsheetApp.openById(ssId).getSheetByName(sheetName) : SpreadsheetApp.openById(ssId).insertSheet(sheetName);
var newText = text.split(" ").slice(1).join(" ");
sheet.appendRow([new Date(),id,name,newText,answer]);
sendText(id,"your text '" + newText + "' is now added to the sheet '" + sheetName + "'");
}
} catch(e) {
sendText(adminID, JSON.stringify(e,null,4));
}
}
This is the notification panel in the GPS platform and how it should be configured with the App Script:
I believe your goal as follows.
You want to split the following value in a cell of Google Spreadsheet.
{"|2020/08/13 18:57|CR-03 FR|0 km|🦂|JESUS SALVADOR GARCIA SCOTT|":""}
Sample formula:
=QUERY(ARRAYFORMULA(SPLIT(REGEXEXTRACT(SUBSTITUTE(A1:A5," km","|km"),"\|(\w.+)\|"),"|",TRUE,FALSE)),"select Col2,Col1,Col6,Col3,Col4")
The flow of this formula is as follows.
Put | to 0 km using SUBSTITUTE.
Retrieve |2020/08/13 18:57|CR-03 FR|0 km|🦂|JESUS SALVADOR GARCIA SCOTT| from {"|2020/08/13 18:57|CR-03 FR|0 km|🦂|JESUS SALVADOR GARCIA SCOTT|":""} using REGEXEXTRACT.
Split it with | using SPLIT.
Rearrange the columns using QUERY.
Result:
When your sample value is used with above formula, it becomes as follows.
Note:
Above proposed answer uses the built-in functions of Google Spreadsheet. If you want to convert above using Google Apps Script, please tell me. At that time, can you provide the sample values including {"|2020/08/13 18:57|CR-03 FR|0 km|🦂|JESUS SALVADOR GARCIA SCOTT|":""} from the response of the API? By this, I would like to think of the solution.
References:
SUBSTITUTE
REGEXEXTRACT
SPLIT
QUERY

How transcribe remove number custom function Excel VBA function to Google Sheets Google Script (Javascript)

I need to transcribe a VBA script to Javascript but i got stuck in the java part
The main meaning is to remove numbers from a text like "texthere 123456789"
My VBA code is:
Function RemoveNum(Txt As String) As String
With CreateObject("VBScript.RegExp")
.Global = True
.Pattern = "[0-9]"
RemoveNum = .Replace(Txt, "")
End With
End Function
My Javascript attempt was:
function RemoveNumbers(RemoveNumbers) {
var RemoveNumbers;
//var str = RemoveNumbers.toString();
var str = RemoveNumbers;
str.Value.replace(/[0-9]/g, '');
}
Or even:
function rn(remvnum) {
var str = remvnum;
var n = str.toString();
var res = n.replace(/[0-9]/gmi, '');
}
What does stop me reaching the result is, the .Replace function needs to be string content otherwise will return error of undefined value, also I can't convert toString because it returns error of undefined value.
This example bellow works well as the name of the function is written in the Google Sheet cell as a custom function, but I didn't achieve the remove number desire:
function styleHyphenFormat(propertyName) {
function upperToHyphenLower(match, offset, string) {
return (offset ? '-' : '') + match.toLowerCase();
}
return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
}
Does someone knows what I did wrong?
Thanks in advance.
Try removeNumbers = removeNumbers.replace(/[0-9]/g, ''); or set a new var like noNums = removeNumbers.replace(/[0-9]/g, '');
You just need to return the replaced value:
function rn(remvnum) {
//var str = remvnum;
//var n = str.toString();
var res = remvnum.toString().replace(/[0-9]/gmi, '');
return res; //Added
}
Google sheets supports regex(re2) as a built-in function unlike excel. So, You don't need macros. Even if you want a global replace, The Find and replace menu works well with regex.
=REGEXREPLACE(A2,"\d",)
or
=ARRAYFORMULA(REGEXREPLACE(A2:A5,"\d",))
\d is digit(==[0-9])

Javascript Web API JSON Parsing Format issue

Hi i have an issue with a few lines of code in JS and formatting my JSON data. Basically in my DB i have a field that is set to nchar(10) but some of the data in the fields are for example only 8 characters long.
The problem i have is when my JS generates a link from JSON data it attaches Spaces to the Data to compensate the (10) characters. For example clicking a link generated from the JS Would generate a link for me like this http://....api/Repo/rep10016
In my JSON it passes in this data
rep10016
But my JS is grabbing this data for the link adding spaces up to 10 as it is a nchar(10) like this.
repoCode = "rep10016 "
But i only want
repoCode = "rep10016"
My JS Code
function displayRepos(repo) {
var table = document.getElementByrCode("rList");
table.innerHTML = "";
for (var i = 0; i < arr.length; i++)
{
var rCode = arr[i].repoCode;
cell2.innerHTML = "<a href='#'rCode='" + rCode + "' " + " >Repo List</a>";
document.getElementByrCode(rCode).onclick = getRepo;
}
function getRepo(rep)
{
var repoUrl = genUrl+rep.target.rCode+"?code="+rep.target.rCode;
......
}
The repoUrl variable is generating a link like this
"http://....api/Repo/rep10016 ?code=rep10016 /"
How can i get my code to only take the actual data and not format it to the nchar(10) format that is in my db??
repoCode.trim() will do the trick.
I would use string.trim();
var orig = 'foo ';
console.log(orig.trim()); // 'foo'

Google Apps Script - Dynamically Add Remove UiApp Form Elements

I am looking to create a Ui form section in my application that will Dynamically Add Remove UiApp Form Elements. I was trying to use the example from App Script Tutorials here
This example works great as far as performing the add remove elements, but when I use the submit button to capture the values, it submits as a JSON.stringify format. When I just want to capture the values only in a text or string format that will be added to a html email.
If there is way to convert JSON.stringify to text, string or get the values only in format, I will continue to use this example.
If not I was wonder if the following Javascript HTML code can be convert into GAS code and able to capture the values for each entry in a HTML email template to using in MailApp.
http://jsfiddle.net/g59K7/
Any suggestions, examples or adjustments to the codes would be greatly appreciated.
Thank you in advance
If you don't want the result to be in a JSON object, then you can adjust the _processSubmittedData(e) function. Right now he has it writing everything to an Object, which is fine. All you have to do is have a way to parse it:
function _processSubmittedData(e){
var result = {};
result.groupName = e.parameter.groupName;
var numMembers = parseInt(e.parameter.table_tag);
result.members = [];
//Member info array
for(var i=1; i<=numMembers; i++){
var member = {};
member.firstName = e.parameter['fName'+i];
member.lastName = e.parameter['lName'+i];
member.dateOfBirth = e.parameter['dob'+i];
member.note = e.parameter['note'+i];
result.members.push(member);
}
var htmlBody = 'Group Name: ' + result.groupName;
for(var a in result.members) {
var member = result.members[a];
var date = member.dateOfBirth;
var last = member.lastName;
var first = member.firstName;
var note = member.note;
htmlBody += first + ' ' + last + ' was born on ' + date + ' and has this note: ' + note;
}
MailApp.sendEmail('fakeEmail#fake.com',"Test Subject Line", "", {htmlBody: htmlBody});
}

Categories

Resources