Is it possible to extract time from a text comment using js? - javascript

First let me apologize for my ignorance when it comes to js.
Is it possible to extract a time from text? For example, i'd like to extract the time from the following text "Results phoned by _ to _ at 2018/04/12 01:31:33. Results confirmed. Read back."
Is this even possible to accomplish this? The software that I use allows for both js and BIRT coding. Any help would be appreciated.
var str = dataSetRow["Comment - Result"];
var time = str.match(/([0-1]\d|2[0-3]):([0-5]\d):([0-5]\d)/g);
time;
Outputs to "Ljava.lang.Object;#bd6334" and i have no idea how to fix it.
I get the "Ljava.lang.Object;#" error for every row of my table with different characters after the #
If I change the code to:
var str = dataSetRow["Comment - Result"];
var time = str.match(/\d{2}:\d{2}:\d{2}/g);
if (time.length>0) time [0];
else "";
I get the desired result but it will only display 1 row of a table with significantly more rows. Am I missing something?

Managed to get it working with some help from our system's manufacturer:
var str = dataSetRow["Comment - Result"];
var time = null;
if (str != null) time = str.match(/\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}/);
var output = "";
if (time != null) {
for (var i = 0; i < time.length; ++i) {
if (i > 0) output += "\n"; // this adds a line break in a computed column expression
output += time[i];
}
}
output;

Related

Is it possible to construct a string in Javascript which has 'variables' built in?

I am working on a PDF with some scripting, and I am applying code to fields using the console and some simple loops to save on repeated efforts. In some cases, I am applying a custom calculation script to a field where one integer needs to change from one field to the next. If all the scripts were the same, I would run this in the debugger console:
var s = "if(this.getField(\"Span A\").value >= 60){\n\
event.value = Math.round(((this.getField(\"Span A\").value*41500 - 1674500)/233));\n\
}else{\n\
event.value = Math.round((this.getField(\"Span A\").value*3500/60));\n\
}";
for (var i = 0; i < this.numFields; i++){
var f = this.getField(getNthFieldName(i));
if(f.name.match(/quant a/i) != null){
var n = f.name.match(/\d/g);
f.setAction("Calculate", s);
}
}
I have many 'Quant' fields, and each group (A, B, etc) will have a similar calculation. The fields are name "Quant A1", "Quant A2" etc. Quant A1 needs to calculate with the input from Span A1.
In the above script, it would be really cool if I could have a variable within the script string that I can pass a value (n) to be plugged in to the string, essentially the same way a function call works.
Is this possible?
Here is my fantasy version of what I imagine it could look like (this is just to further explain my intent; I don't think this would actually work this way):
var s(x) = "if(this.getField(\"Span A\""x").value >= 60){\n\
event.value = Math.round(((this.getField(\"Span A\""x").value*41500 - 1674500)/233));\n\
}else{\n\
event.value = Math.round((this.getField(\"Span A\""x").value*3500/60));\n\
}";
for (var i = 0; i < this.numFields; i++){
var f = this.getField(getNthFieldName(i));
if(f.name.match(/quant a/i) != null){
var n = f.name.match(/\d/g);
f.setAction("Calculate", s(n));
}
}
You could use string litterals if you're useing ES6 and higher.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals?retiredLocale=nl
const greetings = "I'm a variable!";
let string = `Hi! this is a variable: ${greetings}`;
console.log(string);
Otherwise concatenate it with the + operator.
If I understand correctly your question. I think you want to use template literals.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Use backticks instead of " or ' to insert your variables inside a string.
const a ='Cheese'
const b= 'is Delicious'
${a} ${b} will output 'Cheese is Delicious'

Force first letter uppercase in input field

I'm practicing some JavaScript and would love to hear your thoughts regarding this script I wrote. I've managed to make this work. The script makes the first letter of the input value uppercase using the script below. I'm just wondering if this is a good method of doing this/if my steps are in good order just to get better
love to hear more ways of doing so, even making an option to eliminate the caps-lock via keyboard thanks,
// my input var
var strInput =document.querySelector("#inputText > input");
// my function and eventlistener
strInput.addEventListener('input',function() {
//upper case first letter with concatenate string input
var outputString = strInput.value.charAt(0).toUpperCase() + strInput.value.slice(1);
this.value = outputString;
});
As in the comments requested
Here is an example to bind the event to ALL text-inputs (except <textarea> and contenteditable="true")
var txtInputs = document.querySelectorAll("input[type='text'");
//just a simple validation if its not null, undefined or empty
if (txtInputs && txtInputs.length > 0) {
for (var i = 0; i < txtInputs.length; i++) {
var txtInput = txtInputs[i];
txtInput.addEventListener('input', function() {
var outputString = this.value.charAt(0).toUpperCase() + this.value.slice(1);
});
}

Locating MAX Number in a string for a list of records

I am relatively new to JavaScript and trying to get the following achievement.
Lets say we have the following data records.
Example data records:
A_ID_R1_V1
A_ID_R1_V2
A_ID_R2_V1
Basically I am looking for two results:
1.Create a string based on record A_ID_R1_V2.
Input = A_ID_R1_V2
Output = A_ID_R1_V3
My thoughts about this is so locate the MAX V<#> for A_ID_R1_ and then add 1.
2.Create a string based on record A_ID_R2_V1.
Input = A_ID_R2_V1
Output = A_ID_R3_V1
My thoughts about this is so locate the MAX R<#> for all records and then add 1.
Thanks a lot in advance!!!!!!!!
I have strong feeling that this is some kind of school homework...
Anyhow, this will do the job, but its not sophisticated nor very effective
function updateId(letter){
var pos = (letter === 'V')?3:2;
var parts = id.split('_');
var num = parseInt(parts[pos].substring(1,parts[pos].length));
parts[pos] = letter+(num+1);
id = parts.join('_');
logVal(id);
}
try this with regex: http://jsfiddle.net/mig1098/wh6n2oqL/
newEntry = function(entry){
var str2 = entry.replace(/\d+$/,'');
var num = parseInt(entry.replace(/A_ID_R(\d+)_V/,''));
num = num+1;
return str2+num;
}

Google Apps Script random string generating

i am new to Google apps script, i want to create string of random characters in the code given below in variable body2.
function myfunction() {
var files = DriveApp.getFiles();
while (files.hasNext(`enter code here`)) {
Logger.log(files.next().getName());
}
var recipient = Session.getActiveUser().getEmail();
var subject = 'A list of files in your Google Drive';
var body1 = Logger.getLog();
var body2;
for(var i=0;i<6;i++)
{
body2[i]=BigNumber.tostring("Math.floor(Math.random()*11)");
}
body=body1+body2;
MailApp.sendEmail(recipient, subject, body);
};
but when i run this function, it says "TypeError: Cannot find function tostring in object 0. (line 12, file "Code") " i can't understand how to solve this error?
Why we have to multiply random by 11 , can it be multiplied with any integer number?
what if i want that string in only capital letters.!
Some other question
1) i don't have enough knowledge of JavaScript, is it good to learn GAS directly?
2) i can't find proper written material or documentation for GAS , the material available at Google's official site is seems to be updating time by time , what to do then ? any link to material would help me .!
I guess I just figured
function randomStr(m) {
var m = m || 15; s = '', r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i=0; i < m; i++) { s += r.charAt(Math.floor(Math.random()*r.length)); }
return s;
};
Hope someone finds it helpful.
As for a random string use this its better:
Math.random().toString(36). 36 is the base thus will use letters and numbers in the string.
As for gas documentation, the official page is pretty complete. It changes because it constantly improves and adds new services.
I have this charIdGeneration() in my GAS library
function charIdGenerator()
{
var charId ="";
for (var i = 1; i < 10 ; i++)
{
charId += String.fromCharCode(97 + Math.random()*10);
}
//Logger.log(charId)
return charId;
}

javascript to parse csv excel file

I am trying to parse a CSV file I made in Excel. I want to use it to update my Google map. This Google map is in a mobile app that I am developing with Eclipse for Android.
Honestly, I am not sure how to write the JavaScript. Any help will be greatly appreciated. I would be happy to credit your work.
I just want some JavaScript to run when the user hits a button that does the following:
Locates users current location (I have already done this part!)
Locate nearby locations as entered in the .CSV excel file by parsing the .CSV
Display a small link inside every locations notification bubble that says "Navigate" that when the user clicks it, opens google maps app and starts navigating the user to that location from the users current location (Geolocation).
This is the ONLY part I need to finish this application. So once again, any help at all will be greatly appreciated. Thanks everyone!
Honestly, I've been round and round with this problem. The CSV format is not made for easy parsing and even with complicated RegEx it is difficult to parse.
Honestly, the best thing to do is import it into an FormSite or PHPMyAdmin, then re-export the document with a custom separator that is easier to parse than ",". I often use "%%" as the field delimiter and everything works like a charm.
Dont know if this will help but see http://www.randomactsofsentience.com/2012/04/csv-handling-in-javascript.html if it helps...
Additional:
On top of the solution linked to above (my preference) I also used a shed load of stacked regular expressions to token a CSV but it's not as easy to modify for custom error states...
Looks heavy but still only takes milliseconds:
function csvSplit(csv){
csv = csv.replace(/\r\n/g,'\n')
var rows = csv.split("\n");
for (var i=0; i<rows.length; i++){
var row = rows[i];
rows[i] = new Array();
row = row.replace(/&/g, "&");
row = row.replace(/\\\\/g, "\");
row = row.replace(/\\"/g, """);
row = row.replace(/\\'/g, "'");
row = row.replace(/\\,/g, ",");
row = row.replace(/#/g, "#");
row = row.replace(/\?/g, "?");
row = row.replace(/"([^"]*)"/g, "#$1\?");
while (row.match(/#([^\?]*),([^\?]*)\?/)){
row = row.replace(/#([^\?]*),([^\?]*)\?/g, "#$1,$2?");
}
row = row.replace(/[\?#]/g, "");
row = row.replace(/\'([^\']*)\'/g, "#$1\?");
while (row.match(/#([^\?]*),([^\?]*)\?/)){
row = row.replace(/#([^\?]*),([^\?]*)\?/g, "#$1,$2?");
}
row = row.replace(/[\?#]/g, "");
row = row.split(",")
for (var j=0; j<row.length; j++){
col = row[j];
col = col.replace(/?/g, "\?");
col = col.replace(/#/g, "#");
col = col.replace(/,/g, ",");
col = col.replace(/'/g, '\'');
col = col.replace(/"/g, '\"');
col = col.replace(/\/g, '\\');
col = col.replace(/&/g, "&");
row[j]=col;
}
rows[i] = row;
}
return rows;
}
I had this problem which is why I had to come up with this answer, I found on npm a something called masala parser which is indeed a parser combinator. However it didn't run on browsers yet, which is why I am using this fork, the code remains unchanged. Please read it's documentation to understand the Parser-side of the code.
import ('https://cdn.statically.io/gh/kreijstal-contributions/masala-parser/Kreijstal-patch-1/src/lib/index.js').then(({
C,
N,
F,
Streams
}) => {
var CSV = (delimeter, eol) => {
//parses anything beween a string converts "" into "
var innerstring = F.try(C.string('""').returns("\"")).or(C.notChar("\"")).rep().map(a => a.value.join(''));
//allow a string or any token except line delimeter or tabulator delimeter
var attempth = F.try(C.char('"').drop().then(innerstring).then(C.char('"').drop())).or(C.charNotIn(eol[0] + delimeter))
//this is merely just a CSV header entry or the last value of a CSV line (newlines not allowed)
var wordh = attempth.optrep().map(a => (a.value.join('')));
//This parses the whole header
var header = wordh.then(C.char(delimeter).drop().then(wordh).optrep()).map(x => {
x.header = x.value;
return x
})
//allow a string or any token except a tabulator delimeter, the reason why we allow newlines is because we already know how many columns there is, so if there is a newline, it is part of the value.
var attempt = F.try(C.char('"').drop().then(innerstring.opt().map(a=>(a.value.__MASALA_EMPTY__?{value:""}:a))).then(C.char('"').drop())).or(C.notChar(delimeter))
//this is merely just a CSV entry
var word = attempt.optrep().map(a => (a.value[0]?.value??a.value[0]));
//This parses a CSV "line" it will skip newlines if they're enclosed with doublequotation marks
var line = i => C.string(eol).drop().then(word.then(C.char(delimeter).drop().then(word).occurrence(i - 1).then(C.char(delimeter).drop().then(wordh)))).map(a => a.value);
return header.flatMap(a => line(a.header.length - 1).rep().map(b => {
b.header = a.header;
return b
}))
};
var m = {
'tab': '\t',
"comma": ",",
"space": " ",
"semicolon": ";"
}
document.getElementById('button').addEventListener('click', function() {
var val = document.getElementById('csv').value;
var parsedCSV = CSV(m[document.getElementById('delimeter').value], '\n').parse(Streams.ofString(val)).value;
console.log(parsedCSV);
})
})
Type some csv<br>
<textarea id="csv"></textarea>
<label for="delimeter">Choose a delimeter:</label>
<select name="delimeter" id="delimeter">
<option value="comma">,</option>
<option value="tab">\t</option>
<option value="space"> </option>
<option value="semicolon">;</option>
</select>
<button id="button">parse</button>
I would suggest stripping the newlines and the end of the file. Because it might get confused.
This appears to work. You may want to translate the Japanese, but it is very straight-forward to use:
http://code.google.com/p/csvdatajs/

Categories