How to Identify Signed Signature Field In PDF using VB.Net - javascript

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

Related

Password Generator performance : Python vs Javascript (Google apps script)

I created a random code generator script via Google apps script. My goal is to generate 6000 uniques random codes (in spreadsheet) as fast as possible.
The following javascript code crashes with Google spreadsheet + apps script --> too long to execute and the same code under python generates 20,000 random codes in less than 1 second... I'm not a JS ninja, do you have any idea to optimize the JS code below ?
Code JS
function main(nbre_car,nbre_pass,number,letter_maj,letter_min,spec_car){
var nbre_car = 6;
var nbre_pass = 6000;
var number = true;
var letter_maj = false;
var letter_min = false;
var spec_car = false;
var prefixe="FOULE";
return generate_password(nbre_car,nbre_pass,number,letter_maj,letter_min,spec_car,prefixe)
}
function combinaison_possible(char_number,lenght_possible_char){
combinaison_nbre=Math.pow(lenght_possible_char,char_number)
return combinaison_nbre
}
function generate_password(nbre_car,nbre_pass,number=true,letter_maj=false,letter_min=false,spec_car=false,prefixe="") {
if (Number.isInteger(nbre_car)&&Number.isInteger(nbre_pass)){
}
else{
return "Veuillez rentrer un nombre entier pour les champs en bleu"
}
var nbre_car = nbre_car || 10;
var nbre_pass = nbre_pass || 3;
var pass_number="123456789";
var pass_letter_maj="ABCDEFGHIJKLMNPQRSTUVWXYZ";
var pass_letter_min="abcdefghijklmnpqrstuvwxyz"
var pass_spec_car="'(-è_çà)=:;,!."
// Check entry type
// Create an empty map which will contain all password
var col = new Map([]);
var prefixe=prefixe;
var list_char='';
list_char= letter_maj == true ? list_char+pass_letter_maj : list_char
list_char= number == true ? list_char+pass_number : list_char
list_char= letter_min == true ? list_char+pass_letter_min : list_char
list_char= spec_car == true ? list_char+pass_spec_car : list_char
// Teste les combinaisons possible entre le nombre de caractère demandés pour le password et la liste disponible
if (combinaison_possible(nbre_car,list_char.length)>=nbre_pass) {
// Création des mots de passe unique
while(col.size===0||nbre_pass>col.size) {
Logger.log("col.size : "+col.size)
Logger.log("nbre_pass : "+nbre_pass)
search_new_pass=true;
while (search_new_pass==true){
pass=create_one_password(nbre_car,list_char,prefixe)
Logger.log('nom du password : '+pass)
if (verify_unique(col,pass)!=true)
col.set({}, pass);
Logger.log("valeur de col : "+col)
search_new_pass=false;
}
}
}
else{
col = [];
col.push("Vous avez demander trop de mots de passe, cela va créer des doublons,Veuillez diminuer le nombre de mots de passe à afficher");
}
final_values=[...col.values()];
//Logger.log('valeur final de col : '+final_values)
console.log(Array.from(col.values()));
return Array.from(col.values());
}
function create_one_password(nbre_car,list_char,prefixe) {
var nbre_car = nbre_car;
s = '', r = list_char;
for (var i=0; i < nbre_car; i++) {
s += r.charAt(Math.floor(Math.random()*r.length));
}
return prefixe+s;
}
Code Python
import random
def combinaison_possible(char_number,lenght_possible_char):
combinaison_nbre=pow(lenght_possible_char,char_number)
return combinaison_nbre
def generate_password(nbre_car,nbre_pass,number=True,letter_maj=True,letter_min=True,spec_car=True,prefixe="FOULE") :
if(not isinstance(nbre_car,int) and isinstance(not nbre_pass,int)) :
print( "Veuillez rentrer un nombre entier pour les champs en bleu")
nbre_car = nbre_car
nbre_pass = nbre_pass
pass_number="123456789"
pass_letter_maj="ABCDEFGHIJKLMNPQRSTUVWXYZ"
pass_letter_min="abcdefghijklmnpqrstuvwxyz"
pass_spec_car="!##$%^&*()_+"
prefixe=prefixe
list_char=''
col={}
longueur_col=len(col)
list_char= list_char+pass_letter_maj if letter_maj else list_char
list_char= list_char+pass_letter_min if letter_min else list_char
list_char= list_char+pass_number if number else list_char
list_char= list_char+pass_spec_car if spec_car else list_char
if (combinaison_possible(nbre_car,len(list_char))>=nbre_pass) :
while(len(col)==0 or nbre_pass>len(col)):
longueur_col=len(col)
search_new_pass=True
while (search_new_pass==True):
pass_word = prefixe+''.join(random.choice(list_char) for i in range(nbre_car))
if pass_word not in col:
col[longueur_col]=pass_word
search_new_pass=False
print (col)
else :
print("Le nombre de mot de passe à générer est trop important par rapport au nombre de caractères possible")
generate_password(6,20000)
Performance-wise, the main difference between the Apps Script and Python versions is that the Apps Script code logs about 20,000 values in the Apps Script console, which is slow, while the Python code outputs 1 value.
The Apps Script code has several syntactical and semantical errors, including:
verify_unique() is undefined
col.set({}, pass) does not make sense; perhaps use an Array instead of a Map, find if a value is already in the list with col.includes(pass), insert values with col.push(pass), and use col instead of Array.from(col.values()) to retrieve the values
var prefixe = prefixe; is superfluous
See Apps Script at Stack Overflow and Clean Code JavaScript.
I think the code could be quite a bit easier. I did not study your code extensively. But this would be my approach to solve the problem. As you can see it takes less than one second to generate 20'000 passwords.
What actually really takes a long time is the duplicate check.
Aside from thath be careful when generating passwords without a cryptographically secure random algorithm.
Please have a look at this for how to use Crypto.getRandomValues()
const CHARACTER_POOL =
"123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz'(-è_çà)=:;,!.";
const PASSWORDS_TO_GENERATE = 20000;
const PASSWORD_LENGTH = 6;
const PREFIX = "";
const createPassword = () => {
let password = "";
for (let i = 0; i < PASSWORD_LENGTH; i++) {
// this is not secure
password += CHARACTER_POOL.charAt(
Math.floor(Math.random() * CHARACTER_POOL.length)
);
}
return `${PREFIX}${password}`;
};
const generatePassword = () => {
const passwords = [];
while (passwords.length < PASSWORDS_TO_GENERATE) {
const password = createPassword();
if (!passwords.includes(password)) {
passwords.push(password);
}
}
return passwords;
};
const start = new Date().getTime();
const passwords = generatePassword();
console.log(`It took ${(new Date().getTime() - start) / 1000} to generate ${passwords.length} passwords`);
console.log(passwords);
That's a lot of code for what seems a pretty straightforward problem. I didn't look closely at your version, but here's how I might handle the problem. It creates 20000 in about 20 milliseconds on my mid-level machine.
const genPasswords = (chars) => (n, length = 6, pre = '') => Array .from (
{length: n},
() => pre + Array.from({length}, () => chars[~~(Math.random() * chars.length)]) .join('')
)
const pwdGen = genPasswords ("123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz'(-è_çà)=:;,!.")
console.time('generate 20000')
const res = pwdGen (20000, 6, 'FOULE')
console.timeEnd('generate 20000')
console .log (res)
.as-console-wrapper {max-height: 100% !important; top: 0}
I store the characters to use in a closure, returning a function that takes the number to generate, their length, and a prefix.

Problem when printing data from an object array, it appears incorrectly

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]);

Html and Javascript with google script function error

with Google Script i have created this html that send datas to a google sheet taking in input some data from the url (after /exec?P=tonno&Q=3&C=Cliente+1 he takes in input P,Q,C):
<!DOCTYPE html>
<html>
<head>
<title> Modulo di Ordine </title>
<script type="text/javascript">
function doGet(e){
//HtmlService.setTitle("This is MYTITLE");
var result = '<-- Riepilogo Ordine --> \n';
if (e.parameter == 'undefined') {
result += "ERRORE SCONOSCIUTO NELL'ACQUISTO! non verrà inviato l'ordine";
return ContentService.createTextOutput(result);
}
else {
var ID = '1sl0P4auOdX8i67kZ9LA8dGXm59I_fc_tSOaPaOpL1Ek'; // identificativo della cartella di foglio (Spreadsheet ID)
// var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
// var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var Cartella = SpreadsheetApp.openById(ID); // Cartella identificata da ID
var Foglio = Cartella.getSheets()[0]; // nella parentesi quadra il foglio ---> 0 = primo, 1 = secondo, ecc.
var Cella_R = Foglio.getRange(2,5); // riga 2, colonna 5 -> cella E2
var Inserite = Cella_R.getValue() + 1; // numero di righe inserite (letto dal foglio) incrementato di 1
Cella_R.setValue(Inserite); // scrive nel fogio il valore incrementato di «Inserite»
// var Riga = Foglio.getLastRow() + 1;
var Riga = Inserite + 2; // Riga in cui scrivere i dati
result += 'Codice Ordine: #' + Riga; // calcola la riga su cui scrivere i dati
var Cella_D = Foglio.getRange(Riga,1); // D = Data --------------> colonna 1
var Cella_O = Foglio.getRange(Riga,2); // O = Orario ------------> colonna 2
var Cella_T = Foglio.getRange(Riga,3); // T = Temperatura -------> colonna 3
var Cella_U = Foglio.getRange(Riga,4); // U = Umidità relativa --> colonna 4
var Cella_C = Foglio.getRange(Riga,5); // C = Cliente ----------->
var answer = "";
// SpreadsheetApp.setActiveSheet(sheet);
// var rowData = [];
var Giorno_Ora = new Date(); // legge data ed ora attuali
var Data = Utilities.formatDate(Giorno_Ora, "Europe/Rome", 'dd/MM/yyyy'); // estrae la data da Data_Ora
var Orario = Utilities.formatDate(Giorno_Ora, "Europe/Rome", 'HH.mm.ss' ); // estrae l'orario da Data_Ora
Cella_D.setValue(Data); //scrive la Data
Cella_O.setValue(Orario); //scrive l'orario
for (var parametro in e.parameter) {
var valore = Pulisci(e.parameter[parametro]); //estrae il valore del paramentro senza virgolette
switch (parametro) { // condizione case
case 'P':
Cella_T.setValue(valore); // Scrive il prodotto
result += '\nProdotto: ' + valore + ''; // Scrive messaggio risposta
break;
case 'C':
Cella_C.setValue(valore); // Scrive il cliente
result += '\nCliente: ' + valore + ''; // Scrive messaggio risposta
break;
case 'Q':
Cella_U.setValue(valore); // Scrive la quantità
result += '\nQuantità: ' + valore + ' pezzi'; // Scrive messaggio risposta
break;
default: //in caso di errore:
result += "\n\nParametri non validi!. L'ordine non verrà preso in considerazione";
}
} //se tutto va bene passa avanti con il successo
result += '\n\nEseguito con successo! Qualcuno provvederà a prendere in considerazione il suo ordine.';
}
return ContentService.createTextOutput(result); // Restituisce il Riepilogo dell'ordine
}
function Pulisci( value ) {
return value.replace(/^["']|['"]$/g, ""); // sostituisce cosa a cosa???
}
</script>
</head>
<body>
<p>Sicuro di voler procedere con l'ordine?</p> <br>
<input id="clickMe" type="button" value="clickme" onclick="doGet();" />
</body>
</html>
The problem is that when I press the button to call the function doGet(), this is the error and the function doesn't go on:
userCodeAppPanel:5 Uncaught TypeError: Cannot read property 'parameter' of undefined
at doGet (userCodeAppPanel:5)
at HTMLInputElement.onclick (userCodeAppPanel:1)
Can pls somebody help me?
ContentService, SpreadsheetApp, and even doGet(e) are server side functions they run on a Google Server not on your browser. You need to restructure your entire code and utilize some intermediate javascript functions and possibly google.script.run you would be well served to do a little more research in some of the examples provided here at SO.
The idea of using doGet(e) as a clientside function is rather ridculuous because the whole idea is that it's supposed to be an endpoint on the server. It's ridiculous to consider it as a clientside function.
To resolve the issue you are facing, you need to change your button HTML element to the below code -
<input id="clickMe" type="button" value="clickme" onclick="doGet(event);" />
Since you are using inline event handler, you need to pass the event as argument to onClick method. Please refer to this post in-case you have any queries.

Google Script Triggered by Form Submit Sometimes Doesn't Work

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
}

How can I strip text from string?

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/

Categories

Resources