pass an array in a function to string JavaScript - javascript

I have the following problem with the following code:
When I pass the Array to "track" I always get an error, I think it may be because an object is being passed and a String, but I'm not sure and I can't check it.
for (var i = 0; i < data.twKeyword.length; i++){
var stream = client.stream('statuses/filter', {track: data.twKeyword[i]});
}
I have tried:
data.twKeyword
data.twKeyword[i]
[data.twKeyword]
data.twKeyword
data.twKeyword[i]
'data.twKeyword[i]'
data.twKeyword[0].value
data.twKeywprd[0].toString()
And none of these options has given me a positive result.

He creado una variable nueva a la que le he ido pasando los valores del Array:
var x1 = JSON.stringify(data.twKeyword[i].name);
Después como estos valores se mostraban con doble comillas (""), he utilizado el siguiente código para eliminarlas:
x1.replace(/['"]+/g, '')
El código ha quedado así, y funciona:
for (var i = 0; i < data.twKeyword.length; i++){
var x1 = JSON.stringify(data.twKeyword[i].name);
var stream = client.stream('statuses/filter', {track: x1.replace(/['"]+/g, '')});
}

Related

How to exclude consonants in javascript?

I'm making a project that receives the user input, saves it in an array, and then checks if the words are vowels or consonants, everything's fine here, however, i can't get the consonant count correctly.
I discovered two things,
First, if i try to count the consonants while checking each character with the vowels, it gives me the double or triple characters.
Second, i don't know how to count only one time each consonant.
Here's my code:
<!DOCTYPE html>
<html lang="ca">
<head>
<meta charset="utf-8" />
<title>DAW0612-Pràctica 08</title>
<link href="imatges/favicon.ico" type="image/ico" rel="Shortcut Icon"/>
<link href="codi/estil.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header>A l'inrevés</header>
<br />
<div id="missatge"></div>
<h3 id="paraula"></h3>
<h4 id="caracters"></h4>
<p id="consonants"></p>
<p id="vocals"></p>
<p id="espais"></p>
<p id="especials"></p>
<script>
/************ COMENÇEU AQUÍ EL VOSTRE CODI ***************************************************************/
//variables
var frase =[10];
var fraseinreves=[10];
var dump;
var vocales=["a","e","i","o","u"];
var espais = 0;
var j=0;
var vocals = 0;
var consonants = 0;
//programa
frase = window.prompt("Dame una frase cualquiera");
lfrase = frase.length;
for (let i = frase.length -1; i >=0; i--){
//guardamos la frase al reves dentro de la nueva array
fraseinreves[j]=frase[i];
// resultado += frase[i];
if (frase[i] == " "){
espais++;
}
//incrementamos el contador de la array nueva
j++;
}
for (let i = 0; i < frase.length; i ++){
//guardamos los caracteres uno por uno del array a la constante char
const char = frase[i];
//window.alert(char);
window.alert(char);
//creamos un loop para recorrer la array que contiene las vocales
for (let j = 0; j < vocales.length; j++){
//SI EL CONTENIDO DE CHAR, ES IGUAL A ALGUNA VOCAL (ESTAS SE RECORREN EN EL SEGUNDO LOOP), entonces:
if(char == vocales[j]){
window.alert(char);
vocals++;
}
}
//contador para las consonantes.
}
/************ NO TOQUEU EL SEGÜENT CODI ***************************************************************/
document.getElementById("missatge").innerHTML = fraseinreves;
document.getElementById("paraula").innerHTML = "Paraula o frase original: <span>" + frase + "</span>";
document.getElementById("caracters").innerHTML = "Nombre de caràcters: " + lfrase;
document.getElementById("consonants").innerHTML = "Consonants: " + consonants;
document.getElementById("vocals").innerHTML = "Vocals: " + vocals;
document.getElementById("espais").innerHTML = "Espais en blanc: " + espais;
document.getElementById("especials").innerHTML = "Lletres ñ o ç: " + especial;
</script>
<noscript>
El seu navegador no accepta Javascript, si us plau actualitzis a una versió mes moderna.
</noscript>
<br />
<footer>
2016 Departament d'Informàtica - INS LA PINEDA - BADALONA<span>DAW M06-Desenvolupament Web en Entorn Client</span>
</footer>
</body>
</html>
Basically i don't want to use any function like includes() because i want to improve my thinking, and i want to know what i did bad.
Thanks.
this will check if the char is not a vowel. if the char is not a vowel, but is still a letter (checked with regex), then it will add to the consonants counter. not sure how to do with without regex or at least an array of all consonants, because otherwise you might start counting spaces and periods and the like.
//creamos un loop para recorrer la array que contiene las vocales
for (let j = 0; j < vocales.length; j++){
//SI EL CONTENIDO DE CHAR, ES IGUAL A ALGUNA VOCAL (ESTAS SE RECORREN EN EL SEGUNDO LOOP), entonces:
let vocalesFound = false;
if(char == vocales[j]){
window.alert(char);
vocals++;
vocalesFound = true;
}
}
//contador para las consonantes.
if ( !vocalesFound && char.match( /[A-Za-z]/ ) ) consonants++;
}

Parse a SRT file with jQuery Javascript

I'm trying to parse .srt but I get an internal error and I can't figure out what is it.
Here is my code:
var subtitles;
jQuery.get('SB_LKRG-eng.srt', function(data) {
//alert(data);
function strip(s) {
return s.replace(/^\s+|\s+$/g,"");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
//alert(srt);
srt = strip(srt);
//alert(srt);
var srt_ = srt.split('\n\n');
alert(srt_);
var cont = 0;
for(s in srt_) {
st = srt_[s].split('\n');
alert(st);
if(st.length >=2) {
n = st[0];
i = strip(st[1].split(' --> ')[0]);
o = strip(st[1].split(' --> ')[1]);
t = st[2];
if(st.length > 2) {
for(j=3; j<st.length;j++)
t += '\n'+st[j];
}
subtitles[cont].number = n;
subtitles[cont].start = i;
subtitles[cont].end = o;
subtitles[cont].text = t;
//alert(subtitles[cont].start);
}
cont++;
}
});
I can extract the first 4 subtitles and then the code stops and breaks exception: TypeError, I can't understand why...
Here a sample of the subtitles file:
1
00:00:01,000 --> 00:00:04,000
Descargados de www.AllSubs.org
2
00:00:49,581 --> 00:00:52,049
Bueno, tienes que escapar, tengo que ir a jugar
3
00:00:52,084 --> 00:00:55,178
Tengo que encontrar un día que está lleno de nada más que sol
4
00:00:55,220 --> 00:00:57,552
Crucero por la calle, moviéndose al compás
5
00:00:57,589 --> 00:01:00,683
Todos los que conoces está teniendo nada más que diversión
6
00:01:00,726 --> 00:01:03,251
Deja todo detrás de ti
7
00:01:03,295 --> 00:01:06,128
Siente esas palmeras soplan
8
00:01:06,165 --> 00:01:09,157
La gente en el norte no puede encontrar
9
00:01:09,201 --> 00:01:11,829
Están fuera de palear la nieve
10
00:01:11,870 --> 00:01:14,998
El tiempo para moverse, pero no seas lento
11
00:01:15,040 --> 00:01:17,941
En sus marcas, prepárate para ir
Part of the code is from: http://v2v.cc/~j/jquery.srt/jquery.srt.js
Can anyone help me?
Thank you
var PF_SRT = function() {
//SRT format
var pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/gm;
var _regExp;
var init = function() {
_regExp = new RegExp(pattern);
};
var parse = function(f) {
if (typeof(f) != "string")
throw "Sorry, Parser accept string only.";
var result = [];
if (f == null)
return _subtitles;
f = f.replace(/\r\n|\r|\n/g, '\n')
while ((matches = pattern.exec(f)) != null) {
result.push(toLineObj(matches));
}
return result;
}
var toLineObj = function(group) {
return {
line: group[1],
startTime: group[2],
endTime: group[3],
text: group[4]
};
}
init();
return {
parse: parse
}
}();
 
jQuery.get('demo.srt')
.done(function(text) {
try {
//Array with {line, startTime, endTime, text}
var result = PF_SRT.parse(text);
} catch (e) {
//handle parsing error
}
});
Demo
https://jsfiddle.net/5v7wz4bq/
Here is one problem:
o = strip(st[1].split(' --> ')[1]);
At this line, when there isn't any ' --> ' to split, the returned length of the array is 1, which errors when you ask for array item 2.
And here is another:
subtitles[cont].number = n;
....
Neither is the subtitles declared, nor its properties .number, ... etc.
Update
Here is a sample that works (switched the jQuery "read srt file" part for the data)
var data = document.getElementById("data").innerHTML;
data = data.replace(/>/g,">");
function strip(s) {
return s.replace(/^\s+|\s+$/g,"");
}
srt = data.replace(/\r\n|\r|\n/g, '\n');
srt = strip(srt);
var srt_ = srt.split('\n\n');
var cont = 0;
var subtitles = [];
for(s in srt_) {
st = srt_[s].split('\n');
if(st.length >=2) {
var st2 = st[1].split(' --> ');
var t = st[2];
if(st.length > 2) {
for(j=3; j < st.length;j++)
t += '\n'+st[j];
}
subtitles[cont] = { number : st[0],
start : st2[0],
end : st2[1],
text : t
}
console.log(subtitles[cont].number + ": " + subtitles[cont].text);
document.body.innerHTML += subtitles[cont].number + ": " + subtitles[cont].text + "<br>";
cont++;
}
}
<div id="data" style="display:none">1
00:00:01,000 --> 00:00:04,000
Descargados de www.AllSubs.org
2
00:00:49,581 --> 00:00:52,049
Bueno, tienes que escapar, tengo que ir a jugar
3
00:00:52,084 --> 00:00:55,178
Tengo que encontrar un día que está lleno de nada más que sol
4
00:00:55,220 --> 00:00:57,552
Crucero por la calle, moviéndose al compás
5
00:00:57,589 --> 00:01:00,683
Todos los que conoces está teniendo nada más que diversión
6
00:01:00,726 --> 00:01:03,251
Deja todo detrás de ti
7
00:01:03,295 --> 00:01:06,128
Siente esas palmeras soplan
8
00:01:06,165 --> 00:01:09,157
La gente en el norte no puede encontrar
9
00:01:09,201 --> 00:01:11,829
Están fuera de palear la nieve
10
00:01:11,870 --> 00:01:14,998
El tiempo para moverse, pero no seas lento
11
00:01:15,040 --> 00:01:17,941
En sus marcas, prepárate para ir
</div>
It is better to use the following regex to cover them if the number of lines of text in each section increases
/(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/g
View the output on the console
let subtitle = document.getElementById('subtitle').value;
console.log(_subtitle(subtitle));
function _subtitle(text) {
let Subtitle = text;
let Pattern = /(\d+)\n([\d:,]+)\s+-{2}\>\s+([\d:,]+)\n([\s\S]*?(?=\n{2}|$))/g;
let _regExp = new RegExp(Pattern);
let result = [];
if (typeof (text) != "string") throw "Sorry, Parser accept string only.";
if (Subtitle === null) return Subtitle;
let Parse = Subtitle.replace(/\r\n|\r|\n/g, '\n');
let Matches;
while ((Matches = Pattern.exec(Parse)) != null) {
result.push({
Line: Matches[1],
Start: Matches[2],
End: Matches[3],
Text: Matches[4],
})
}
return result;
}
<textarea id="subtitle">1
00:00:00,000 --> 00:00:00,600
Hi my friends
2
00:00:00,610 --> 00:00:01,050
In the first line, everything works properly
But there is a problem in the second line that I could not solve :(
3
00:00:01,080 --> 00:00:03,080
But then everything is in order and good
4
00:00:03,280 --> 00:00:05,280
You do me a great favor by helping me. Thankful</textarea>

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
}

To count number of rows in a table if the rows were created after the DOM loaded

I create rows after the DOM loaded, but I want to know how to count number of rows for eliminate the last.
I have this.
<script type="text/javascript">//Procesamiento del formulario.
$(document).ready(function(){
var cuentaTr = $('#elementos >tbody >tr').length - 1; //Cuenta el número de filas que tiene la tabla originalmente, es 1.
$('#agregar').click(function(){ //Clic en el botón que agrega nueva fila.
cuentaTr++; //Es el número de fila que le corresponde a cada una que se crea.
var nume = $('#elementos >tbody >tr >td').length; //Obtener el número de celdas
var capa = document.getElementById("elementos"); //Obtener el elemento con el id elementos
var tr = ("tr"); //Crear una tag tr
capa.appendChild(tr); //Agregar la tag al elemento con id elementos.
var nuevaLetra = "A"; //La variable con la que se le asigna una letra a cada columna.
for (var i = 1; i <= nume; i++) {
$('<td><input type="text" class="prueba" id="'+nuevaLetra+cuentaTr+'" name="columna'+nuevaLetra+cuentaTr+'" required/></td>').appendTo('#elementos'); //Creación de nuevo input. THIS IS THE IMPORTANT!
var ASCII = nuevaLetra.charCodeAt(); //Obtener código ASCII
var aumento = ((ASCII+1 >= 65 && ASCII+1 <= 90) || (ASCII+1 >= 97 && ASCII+1 <= 122)) ? ASCII+1 : ASCII; //Incremenar la letra
var nuevaLetra = String.fromCharCode(aumento); //Tranformar el código a letra.
};
if (cuentaTr == 2){
$('<button type="button" id="eliminame">-</button>').insertAfter('#agregar'); //Creación del botón de eliminación de filas
};
});
$(document).on('click', '#eliminame', function(){ //Función que elimina las filas HERE IS MY DUDE.
$('#elementos tbody tr:last').remove(); //I WANT TO REMOVE THE LAST ROW. THIS CODE ELIMINATE ONLY THE ROWS CREATE WHEN DOM LOADED.
cuentaTr--;
if (cuentaTr == 1) {
$(this).remove();
};
});
});
</script>
What I can to do?
Thank you!
I'm sorry for my English. I can't speak English well.
Looks like there are some problems on how the tr is appended to the table, try
$(document).ready(function () {
var cuentaTr = $('#elementos >tbody >tr').length - 1; //Cuenta el número de filas que tiene la tabla originalmente, es 1.
$('#agregar').click(function () { //Clic en el botón que agrega nueva fila.
cuentaTr++; //Es el número de fila que le corresponde a cada una que se crea.
var nume = $('#elementos >tbody >tr:first >td').length; //Obtener el número de celdas
var capa = $("#elementos"); //Obtener el elemento con el id elementos
var tr = $('#tr').appendChild(tr); //Agregar la tag al elemento con id elementos.
var nuevaLetra = "A"; //La variable con la que se le asigna una letra a cada columna.
for (var i = 1; i <= nume; i++) {
$('<td><input type="text" class="prueba" id="' + nuevaLetra + cuentaTr + '" name="columna' + nuevaLetra + cuentaTr + '" required/></td>').appendTo(tr); //Creación de nuevo input. THIS IS THE IMPORTANT!
var ASCII = nuevaLetra.charCodeAt(); //Obtener código ASCII
var aumento = ((ASCII + 1 >= 65 && ASCII + 1 <= 90) || (ASCII + 1 >= 97 && ASCII + 1 <= 122)) ? ASCII + 1 : ASCII; //Incremenar la letra
var nuevaLetra = String.fromCharCode(aumento); //Tranformar el código a letra.
};
if (cuentaTr == 2) {
$('<button type="button" id="eliminame">-</button>').insertAfter('#agregar'); //Creación del botón de eliminación de filas
};
});
$(document).on('click', '#eliminame', function () { //Función que elimina las filas HERE IS MY DUDE.
$('#elementos tbody tr:last').remove(); //I WANT TO REMOVE THE LAST ROW. THIS CODE ELIMINATE ONLY THE ROWS CREATE WHEN DOM LOADED.
cuentaTr--;
if (cuentaTr == 1) {
$(this).remove();
};
});
});
var cuentaTr = $('#elementos >tbody >tr').length - 1; (already in your code) should give you the number of rows (minus one). Maybe make a jsfiddle so we can debug what's going on?

onChange event not working on IE9/10 when there are other events?

I'm facing this embarrassing situation. First, I'm on IE 10 right now, but this problem has been detected on IE9 as well. I have this input field and I need 2 events to work on it:
- onKeyUp, to check if the field's value is numeric; and
- onChange, to run some JS when the right number is inputted
If assigned separately, they work just fine. However, whenever I set these 2 events on the input field, the onChange event won't trigger, no matter what. All the other JS on this page has been stripped to prevent interference.
Below is the JS code for the onKeyUp:
<script>
function CampoNumerico(campo){
var valor = campo.value;
var novoValor = '';
var pontoPosicao = '';
if (isNaN(valor)){ // se nao for numero, devemos retornar o campo ao ultimo valor valido
alert(valor + " nao eh um numero valido");
novoValor = campo.defaultValue;
}
else{ //sendo um numero, buscamos a posicao de sua eventual virgula
valor = valor.split('');
for (var i = 0; i < valor.length; i++){
if (valor[i] == '.' && pontoPosicao == ''){
pontoPosicao = i;
}
}
// se nao houver ponto, o novo valor do campo sera igual ao valor de entrada da funcao
if ( pontoPosicao == ''){
for (var i = 0; i < valor.length; i++){
novoValor += valor[i];
}
}
else{ // se houver o ponto, registramos o novo valor igual ao valor de entrada, ate o limite de casas decimais
var tamanho = ((pontoPosicao + 3) < valor.length)? pontoPosicao + 3 : valor.length;
for (var i = 0; i < tamanho; i++){
novoValor += valor[i];
}
}
if (pontoPosicao != '' && pontoPosicao < (valor.length - 3)){ // se houver um ponto e mais de 2 casas decimais, alertamos o usario e desconsideramos as casas adicionais
alert("Aviso: " + campo.value + " tem mais de 2 casas decimais; serão consideradas apenas as primeiras casas - " + novoValor);
}
}
// terminamos por atualizar o valor do campo
campo.value = novoValor;
} // fim da CampoNumerico
</script>
Below is the field I'm trying to assign this script to:
<input type='text' name='campo' value='0' onchange='alert("1")' onkeyup='CampoNumerico(this)'>
At this point I just want to alert "1" when the onchange is triggered, but I'm unable to do even this simple action...
Interestingly, this coding works on other browsers just fine - Chrome & Firefox. Can anyone help me with this embarrassing situation? Thanks in advance for any thoughts.
EDIT - input field now visible separately

Categories

Resources