I have one variable holding single line string which is html element like this.
var des = "<p> --Sometext before-- FI: This is fi name, This is fi manufacturer <br /> SE:This is se name, This is se manufacturer <br /> EN: This is en name, This is en manufacturer</p>";
I want to select everything after FI: until comma sign into one variable and after comma sign until tag into another variable. Also for SE: and EN: too.
For example, result will be like this.
var fi_name = "This is fi name";
var fi_manufacturer = "This is fi manufacturer";
var se_name = "This is se name";
var se_manufacturer = "This is se manufacturer";
var en_name = "This is en name";
var en_manufacturer = "This is en manufacturer";
Note, the string change dynamically but still have same pattern.
For example:
<p> --Sometext before-- FI:[name],[manufacturer]<br/ >SE:[name],[manufacturer]<br/ >FI:[name],[manufacturer]</p>
You can have a look at demo in JsFiddle.
Now it's throwing null error.
Edited v v v
It's not working in live website. The des variable is fully look like this.
Please see http://jsfiddle.net/AM8X2/ It's throwing null again.
You can just look for the specified pattern and extract the relevant information from there:
var des = "<p>FI: This is fi name, This is fi manufacturer <br /> SE:This is se name, This is se manufacturer <br /> EN: This is en name, This is en manufacturer</p>";
var f = function(w, s) {
return new RegExp(w + ':([^,]+)').exec(s)[1];
}
fi = f('FI', des);
se = f('SE', des);
en = f('EN', des);
w + ':([^,]+)' can be explained as: get me the value after the colon of w in s
here is the updated fiddle.
A more complete solution, one that handles all HTML tags would be the following:
var f = function(w, s) {
var el = document.createElement('div'), arr;
el.innerHTML = s;
arr = (new RegExp(w + ':([^\n]+)').exec(el.innerText)[1]).split(',');
return {
manufacturer: arr[1],
name: arr[0]
}
}
fi = JSON.stringify(f('FI', des));
se = JSON.stringify(f('SE', des));
en = JSON.stringify(f('EN', des));
The fiddle for this is here
To access any of these in variables (without the JSON.stringify(), the direct method return, i.e. f('SE', des)), you would do:
// for fi manufacturer
fi.manufacturer
// for en name
en.name
// etc..
in my opinion, by using this, you have a much more modular approach, and less chance of error.
I changed your jsFiddle to this:
http://jsfiddle.net/11684/raPDd/4/
I added upper case letters and spaces and comma's to your regex, so it doesn't return null (because no match was found) and the rest was fine.
The result:
var fi,se,en;
var des = "<p>FI: This is fi name, This is fi manufacturer <br /> SE:This is se name, This is se manufacturer <br /> EN: This is en name, This is en manufacturer</p>";
var match = des.match(/<p>FI:([a-zA-Z ,]+)<br \/> SE:([a-zA-Z ,]+)<br \/> EN:([a-zA-Z ,]+)<\/p>/);
fi = match[1];
se = match[2];
en = match[3];
alert("[FI]: " + fi + "\n[SE]:" + se + "\n[EN]:" + en);
EDIT:
I didn't see you needed the name and manufacturer in separate variables, I edited the fiddle: http://jsfiddle.net/11684/raPDd/5/ to this:
var fi,se,en;
var des = "<p>FI: This is fi name, This is fi manufacturer <br /> SE:This is se name, This is se manufacturer <br /> EN: This is en name, This is en manufacturer</p>";
var match = des.match(/<p>FI:([a-zA-Z ,]+)<br \/> SE:([a-zA-Z ,]+)<br \/> EN:([a-zA-Z ,]+)<\/p>/);
fi = match[1];
se = match[2];
en = match[3];
//After that just split on the comma:
var fi_name = fi.split(",")[0];
var fi_manu = fi.split(",")[1];
var en_name = en.split(",")[0];
var en_manu = en.split(",")[1];
var se_name = se.split(",")[0];
var se_manu = se.split(",")[1];
Here's a possible solution:
var des = "<p> --Sometext before-- FI: This is fi name, This is fi manufacturer <br /> SE:This is se name, This is se manufacturer <br /> EN: This is en name, This is en manufacturer</p>";
var matches = des.match( /([A-Z]{2}):\s*([^,]+?)\s*,\s*([^<$]+?)\s*(?=<|$)/g );
var results = [];
for ( var i = 0; i < matches.length; i++ ) {
var res = matches[ i ].match( /([A-Z]{2}):\s*([^,]+?)\s*,\s*([^<$]+?)\s*(?=<|$)/ );
var abbr = res[ 1 ].toLowerCase();
results[ abbr + '_name' ] = res[ 2 ];
results[ abbr + '_manufacturer' ] = res[ 3 ];
}
console.log( results );
Try it out in this fiddle: http://jsfiddle.net/bukfixart/QB5qu/
Related
I have this program where there are a series of registered students and when they put their name, their data and the name of the teacher they have assigned.
When inserting a new student, the only thing that it does to me correctly is to print if the teacher exists or not, since the student's data does not show them to me, and finally I have a failure in the last line of the javascript code related to innerhtml , the error in question is:
Uncaught TypeError: Cannot set properties of null (setting
'innerHTML')
at mensaje.js:74
now the code:
html:
<button onclick="infoalumno()">Informacion del alumno</button>
<button onclick="insertar()">Introducir nuevo alumno</button>
<div id="info"></div>
and javascript code:
function alumno(nombre, edad, nota, profesor) {
this.nombre = nombre;
this.edad = edad;
this.nota = nota;
this.profesor = profesor;
}
function profesor(nombre, asginatura) {
this.nombre = nombre;
this.asginatura = asginatura;
}
var profesores = new Array(3);
profesores[0] = new profesor("Paco","Plastica");
profesores[1] = new profesor("Anton","Biologia");
profesores[2] = new profesor("Jacinto","Lengua");
var alumnos = new Array(2);
alumnos[0] = new alumno("Jose",24,7,profesores[0]);
alumnos[1] = new alumno("Jacobo",23,7,profesores[2]);
function infoalumno() {
var buscar = prompt("Inserta el nombre del alumno que quieres buscar");
var comprobar = false
for (let i = 0; i < alumnos.length; i++) {
if (buscar == alumnos[i].nombre) {
document.write("Nombre" + alumnos[i].nombre + "<br>Edad:" + alumnos[i].edad + "<br>Nota:" + alumnos[i].nota + "<br>Profesor:" + alumnos[i].profesor.nombre);
comprobar = true;
}
if (comprobar == false) {
document.write("Alumno " + buscar + "no existe");
}
}
}
function insertar() {
var comprobar2 = false;
var nombre = prompt("Insertar el nombre del alumno");
var edad = parseInt(prompt("Ingresa la edad"));
var nota = parseInt(prompt("Ingresa la nota"));
var profesor = prompt("¿Quien es el profesor?");
for (let i = 0; i < profesores.length; i++) {
if (profesor == profesores[i].nombre) {
var newalumno = new alumno(nombre, edad, nota, profesor[i]);
alumnos.push(newalumno);
comprobar2=true;
break;//la sentencia break permite terminar de forma abrupta un bucle y la sentencia continue permite saltarse algunas repeticiones del bucle. ... La utilidad de break es terminar la ejecución del bucle cuando una variable toma un determinado valor o cuando se cumple alguna condición.
}
}
if(comprobar2==false){
document.write("Profesor "+profesor+" no existe");
}
}
var infoprofesor ="Profesores";
for (let i = 0; i < profesores.length; i++) {
infoprofesor = infoprofesor + profesores[i].nombre+"<br>";
}
document.getElementById("info").innerHTML = infoprofesor;
1)
The teacher does not appear his name instead appears [object Object]
In this code
document.write("Nombre" + alumnos[i].nombre + "<br>Edad:" + alumnos[i].edad + "<br>Nota:" + alumnos[i].nota + "<br>Profesor:" + alumnos[i].profesor);
This alumnos[i].profesor will be a Profesor object like from calling new Profesor(...). If you wanted to show the name it would look like alumnos[i].profesor.nombre
2)
And when inserting a new student, the only thing that it does to me
correctly is to print if the teacher exists or not.
var profesor = prompt("¿Quien es el profesor?");
for (let i = 0; i < profesores.length; i++) {
if (profesor == profesores[i].nombre) {
var newalumno = new alumno(nombre, edad, nota, profesor);
alumnos.push(newalumno);
comprobar2=true;
break;
}
}
In this loop you have a related issue. The result from prompt will just be a string (your var profesor). However when you go to make your new alumno it expects a profesor object (with nombre/asignatura).
In this case you're probably want to do var newalumno = new alumno(nombre, edad, nota, profesores[i]);
I have a problem when writing a html code in chat that appears in the box, this is dangerous and ugly to see, is there any javascript or html code to block html and cone files ?
if I write on the text input a html code such as appears in the box ie the code works, how do I block there is a way or some code to paste in the text?
Here is input:
<input type="text" name="chat" id="chattbox" placeholder="Ask what you want." onfocus="placeHolder ()">
var messages = [],
lastUserMessage = "",
botMessage = "",
botName = 'Jacob', t
talking = true;
function chatbotResponse() {
talking = true;
botMessage = "non ho capito";
var hi = ['Ciao {$mybb->user['username']}','mhhh','forte','haha','Chi sei?', 'mi vuoi bene?', 'Sono un bot questo non significa che io sia scemo', 'grande', 'boh', 'bah...', 'sei forte haha', 'ti piace stertix?', 'ok','se lo dici tu.','come vuoi', 'ho fame', 'Mi sto pulendo il naso... Quello che non ho :(', 'Hai ragione', 'Sei un grande', 'aaahhhhhhh!!!', 'mlmlml', 'cavolo', 'wow', 'figo', 'come mai?', 'forse', 'Si', 'No', 'mi piace parlare con te <3', 'spacco bottilia ammazzo familia', 'ti amo', 'ti voglio bene', 'che canzone ti piace?', 'che cantante ti piace?', 'so che pensi che sia stupido ma non lo sono.', 'ma lo sarai tu.', 'va bene', 'bello', 'molto', 'molto bello', 'cosa ne pensi di stertix?', ':D', ':)', ';)', '<3', ':O', 'Che fai?', 'quale?', 'quale', 'eh', 'grave', 'eccellente', 'giusto', 'grazie', 'eccellente', 'ottimo', 'ue guaglio bell stu orolog',];
botMessage = hi[Math.floor(Math.random()*(hi.length))];
var n = lastUserMessage.search(/\b(gatto|gatti)\b/i);
if (n !== -1) {
botMessage = 'Amo i gatti!';
}
var n = lastUserMessage.search(/\b(ciao|salve|ehi|we)\b/i);
if (n !== -1) {
var vr = ['Ciao {$mybb->user['username']}!', 'Ciao fra', 'Ciao amico', 'ehi {$mybb->user['username']}!', 'We {$mybb->user['username']}!',];
botMessage = vr[Math.floor(Math.random()*(vr.length))];
}
var n = lastUserMessage.search(/\b(bene)\b/i);
if (n !== -1) {
var vr = ['Ottimo','Meglio cosi', 'Mi fa piacere',];
botMessage = vr[Math.floor(Math.random()*(vr.length))];
}
var patt = /\b(cani)\b/i;
var result = patt.exec(lastUserMessage);
if (result) {
botMessage = 'Amo i ' + result[0];
}
var n = lastUserMessage.search(/\b(animali)\b/i);
if (n !== -1) {
botMessage = 'Amo gli animali!';
}
var n = lastUserMessage.search(/\b(come va|come stai)\b/i);
if (n !== -1) {
var vir = ['Benissimo, tu?','Bene dai...', 'bene tu?', 'male, tu?', 'Malissimo, tu?', 'diciamo, tu?',];
botMessage = vir[Math.floor(Math.random()*(vir.length))];
}
var n = lastUserMessage.search(/\b(che fai|che stai facendo)\b/i);
if (n !== -1) {
var vuyr = ['Nulla, parlo con te, tu che fai?','Niente, tu?', 'Mi annoio, tu?', 'Mi vedo film zozzi, tu?', 'cerco un modo per conquistare il mondo... na scherzo sono un bot pirla, tu che fai?', ];
botMessage = vuyr[Math.floor(Math.random()*(vuyr.length))];
}
I've commented the code -- basically, if a user enters a < and then, at some point later, types a > then everything between them is stripped out by regex. From what you're describing, this seems like what you're looking for.
var filterHtmlCodes = function() {
/*****
* Here, we're going to go through and strip
* any tags -- words wrapped in <>. Thus,
* users can still enter either symbol, but
* entering both will immediately strip the
* tag value. I'm triggering on every
* keyup, but it could as easily be done on every
* change, so as to block copy/paste, for example.
*****/
myChatEl.value = myChatEl.value.replace(/<(?:.|\n)*?>/gm, '')
};
// And I prefer to add my listeners outside of my HTML.
var myChatEl = document.querySelector("#chattbox");
myChatEl.addEventListener("keyup", filterHtmlCodes)
<input type="text" name="chat" id="chattbox" placeholder="Ask what you want.">
I have a script that reads answers from a Google form when it is sent. The script is bound to a spreadsheet, that captures all answers. The script generates a PDF with some information and sends it to a user via GmailApp, and stores the PDF inside a Drive folder. But sometimes the script doesn't work. The answers are always stored in the spreadsheet, but despite this, the script doesn't run. I have checked the "Execution transcript", but it contains information about the last successful execution.
How can I guarantee that the script always runs?
Can anyone explain why this happens?
Code
//ID del template
var docTemplate = "Template ID Here";
//Nombre de la copia
var docName = "biovenCIP";
//FUnción principal para generación y envío de constancia
function onFormSubmit(e){
//Leyendo datos del formulario
var d = new Date();
var registration_date = e.values[0];
var first_name = e.values[1];
var second_name = e.values[2];
var first_lastname = e.values[3];
var second_lastname = e.values[4];
var document_type = e.values[5];
var document_number = e.values[6];
var email_address = e.values[7];
var occupation = e.values[8];
var category = e.values[9];
var payment_number = e.values[10];
var payment_date = e.values[11];
//Inicializando mensaje opcional
var occupation_message = " ";
//Generando el nombre completo
if(second_name.localeCompare("") != 0){
second_name = " " + second_name;
}
if(second_lastname.localeCompare("") != 0){
second_lastname = " " + second_lastname;
}
var full_name = first_name + second_name + " " + first_lastname + second_lastname;
full_name = full_name.replace(/\s+/g," ");
//Generando compia del template
var copyID = DocsList.getFileById(docTemplate).makeCopy(docName + '_' + document_number).getId();
var copyDoc = DocumentApp.openById(copyID);
var copyBody = copyDoc.getActiveSection();
//Reemplazando texto en el template
copyBody.replaceText('keyDate', registration_date);
copyBody.replaceText('keyFullName', full_name);
copyBody.replaceText('keyIDType', document_type);
copyBody.replaceText('keyIDNumber', document_number);
copyBody.replaceText('keyEmail', email_address);
copyBody.replaceText('keyOccupation', occupation);
switch(occupation){
case "Estudiante de pregrado":
occupation_message = "(presente carnet el primer día del evento)";
var payment_worth = 100.00;
break
case "Estudiante de postgrado":
occupation_message = "(presente carnet el primer día del evento)";
var payment_worth = 150.00;
break
case "Profesional":
var payment_worth = 200.00;
break
}
copyBody.replaceText('keyOMessage', occupation_message);
copyBody.replaceText('keyCategory', category);
copyBody.replaceText('keyPaymentNum', payment_number);
copyBody.replaceText('keyPaymentDate', payment_date);
copyBody.replaceText('keyPayment', payment_worth)
copyDoc.saveAndClose();
//Convertir temporalmente a PDF
var pdf = DocsList.getFileById(copyID).getAs("application/pdf");
//Adjuntando PDF y enviado correo electrónico
var reply_email = "info#bioven.org.ve";
var bcc_email = "congresobioven#gmail.com";
var subject = "Constancia de inscripción - BIOVEN 2015";
var body = "Estimado " + full_name + ",<br/><br/> A través de este correo electrónico le hacemos entrega de su constancia de inscripción en el V Congreso Venezolano de Bioingeniería - BIOVEN 2015, la cual deberá presentar el primer día del congreso durante la verificación de registro.<br/><br/> Agradecidos,<br/><br/> <b>Comité Organizador del BIOVEN 2015</b>";
GmailApp.sendEmail(email_address, subject, body, {name: 'Congreso BIOVEN 2015', bcc: bcc_email, htmlBody: body, replyTo: reply_email, attachments: pdf});
//Guardando PDF en Drive
var folder_id = "Folder ID Here";
DriveApp.getFolderById(folder_id).createFile(pdf);
//Borrando archivo DOC temporal
DocsList.getFileById(copyID).setTrashed(true);
}
Try defining your variable payment_worth higher up in the code:
function onFormSubmit(e){
//Leyendo datos del formulario
var d = new Date();
//Other var definitions
var payment_worth = 0;
Give it an initial value of zero. Presently, if your Case/Select ever fails, the variable payment_worth would be undefined.
Just an idea. Don't know if it's a good idea. ;)
Case Select would look like this:
switch(occupation){
case "Estudiante de pregrado":
occupation_message = "(presente carnet el primer día del evento)";
payment_worth = 100.00;
break
case "Estudiante de postgrado":
occupation_message = "(presente carnet el primer día del evento)";
payment_worth = 150.00;
break
case "Profesional":
payment_worth = 200.00;
break
}
For some reason this code is giving a lint. I can't really figure out why.
It says: 'was expecting a assignment or function call, and instead saw an expression.'
What does that mean?
window.onload = function (){
function SuspectOne (naam, leeftijd, wie){
this.naam = Spencer Hawes;
this.leeftijd = 22;
this.wie = zoon van de man;
}
function SuspectTwo (naam, leeftijd, wie){
this.naam = Tyrone Biggums;
this.leeftijd = 28;
this.wie = lokale herionejunk;
}
function SuspectThree (naam, leeftijd, wie){
this.naam = Ellie Campbell Hawes;
this.leeftijd = 40;
this.wie = vrouw van de man;
}
var verdachten = new Array[];
verdachten[0] = new Verdachte("Spencer Hawes", 22, "zoon van de man");
verdachten[1] = new Verdachte("Tyrone Biggums", 28, "lokale herionejunk");
verdachten[2] = new Verdachte("Ellie Spencer Hawes", 40, "vrouw van de man");
for(x=0; x<verdachten.length; x++){
console.log("De verdachte is de " + verdachten[x].leeftijd + "jaar oud " + verdachten[x].naam + ", de " + verdachten[x].wie);
}
};
Can someone help me with this? I would really like a lint free code.
Looks like you have strings not in quotes:
this.naam = Spencer Hawes;
should be
this.naam = 'Spencer Hawes';
also
this.wie = 'zoon van de man';
It also might give errors for the new Array[] stuff, you should probably use object literals:
var verdachten = [];
Also the linter should give line numbers so you can easily find what's wrong.
Hi I'm looking for a way to locate signature field on PDF using VB.Net Or JavaScript and Acrobat and then I want to check if it is signed or not. Here is what I have so far:
Dim page As Acrobat.CAcroPDPage
Dim annot As Acrobat.CAcroPDAnnot
page = acroPDDoc.AcquirePage(0)
For i = 0 To page.GetNumAnnots - 1
annot = page.GetAnnot(i)
Next
Im finding the annotations but I dont know how to check if it is signature field or not. Thanks
Using via JavaScript, you can use the this.getNthFieldName(i) to get all the fieldnames on the acrobat document. You would then have to locate the correct field with the "field.type.localeCompare("signature") == 0" to ensure that is the field you are looking for. After that, just process through it to determine if there is a signature or not.
Below is a snippet of code that I used to determine if there was a digital signature present.
for(var i = 0; i < this.numFields; i++) {
var a = this.getNthFieldName(i);
var field = this.getField(a);
if(field.type.localeCompare("signature") == 0) {
var s = field.signatureInfo();
if( s.name == null) {
console.println("Digital Signature Not Present.");
return -1;
}else {
console.println("Digital Signature Present.");
return 0;
}
}
}
Dim theForm As Acrobat.CAcroPDDoc
Dim jso As Object
theForm = CreateObject("AcroExch.PDDoc")
theForm.Open("C:\Temp\Maru\DeclaracionJurada.pdf")
jso = theForm.GetJSObject
'Verifica que la firma sea valida
Dim signatureOne = jso.getField("Signature2")
Dim oState = signatureOne.SignatureValidate()
Select Case oState
Case Is = -1
ListBox1.Items.Add("Estado : Sin Firma ")
Case Is = 0
ListBox1.Items.Add("Estado : Firma en blanco ")
Case Is = 1
ListBox1.Items.Add("Estado : No conoce el estado de la firma ")
Case Is = 2
ListBox1.Items.Add("Estado : Firma invalida ")
Case Is = 3
ListBox1.Items.Add("Estado : La firma es valida, pero la identidad del firmante no se pudo verificar ")
Case Is = 4
ListBox1.Items.Add("Estado : Firma e identidad son validas ")
End Select
'Extrae la info del firmante, nombre y fecha de la firma
Dim signatureInformation = signatureOne.signatureInfo
ListBox1.Items.Add("Firmante " & signatureInformation.name)
ListBox1.Items.Add("Fecha " & signatureInformation.Date)
'Extrae la info del certificado
Dim signatureCertificate = signatureInformation.certificates
ListBox1.Items.Add("Emitido a : " & signatureCertificate(0).subjectDN.serialNumber)
ListBox1.Items.Add("Numero de Serie : " & signatureCertificate(0).serialNumber)
ListBox1.Items.Add("Valido desde : " & signatureCertificate(0).validityStart)
ListBox1.Items.Add("Valido hasta : " & signatureCertificate(0).validityEnd)
ListBox1.Items.Add("Para : " & signatureCertificate(0).subjectDN.o)
ListBox1.Items.Add("Tipo : " & signatureCertificate(0).subjectDN.ou)
ListBox1.Items.Add("Emitido Por : " & signatureCertificate(0).issuerDN.cn)
How to identify signed signature field in PDF using VB.Net
Dim gApp As Acrobat.CAcroApp
Dim gPDDoc As Acrobat.CAcroPDDoc
Dim jso As Object
Dim fname As String
gApp = CreateObject("AcroExch.App")
gPDDoc = CreateObject("AcroExch.PDDoc")
If gPDDoc.Open("C:\Temp\Solicitud de empleo.pdf") Then
jso = gPDDoc.GetJSObject
For i = 0 To jso.numFields - 1
fname = jso.getNthFieldName(i)
ListBox1.Items.Add("Campo : " & fname & " valor: " & jso.getField(fname).value)
MessageBox.Show(jso.getField(fname).type)
Next
End If