how to get the opening and closing times and save in two variables with javascript?

0

How to get the start and end times and save in two variables with javascript?

var hora1 =  '9h - 22h'
   var hora2 = '12h - 21h'

    var1 = 9
    var2 = 22
    var3 = 12
    var4 = 21

using substring I could not because they values vary dynamically ..

    
asked by anonymous 08.06.2018 / 22:56

3 answers

1
var hora1 = '9h - 22h'.split('-'); //uso o 'split' para isolar cada valor

var h1 = hora1[0].replace(/h\s|h|\s/g, ''); //uso 'replace' com uma 
var h2 = hora1[1].replace(/h\s|h|\s/g, ''); //expressão regular para remover espaços e a letra 'h'
    
08.06.2018 / 23:11
1

You can do this with while by checking whether the hora variables exist and by creating the var variables by separating the values with .split :

var hora1 = '9h - 22h';
var hora2 = '12h - 21h';

var hora = var_ = 1;

while(window['hora'+hora]){ // enquanto existir variáveis iniciando com "hora" + um número sequencial começando do 1
   
   var quebra = window['hora'+hora].split(" - "); // converto em array com dois índices
   
   window['var'+var_] = parseInt(quebra[0]); // primeiro valor pegando apenas o número
   window['var'+(var_+1)] = parseInt(quebra[1]); // segundo valor pegando apenas o número
   hora++; // incremento em +1
   var_ += 2; // incremento em +2
}

console.log(var1, var2, var3, var4);
  

Remember that to use window[] , the variables must have global scope.

If these are just two variables ( hora1 and hora2 ), you can do this:

var hora1 = '9h - 22h'
 ,  hora2 = '12h - 21h'

 ,  quebra = hora1.split(" - ")
 ,  var1 = parseInt(quebra[0])
 ,  var2 = parseInt(quebra[1])

 ,  quebra = hora2.split(" - ")
 ,  var3 = parseInt(quebra[0])
 ,  var4 = parseInt(quebra[1]);

console.log(var1, var2, var3, var4);
    
08.06.2018 / 23:11
0

You can use the String.prototype.split ()

var hora1 = '9h - 22h'
var hora2 = '12h - 21h'

var hora1array = hora1.split('-')    
var hora2array = hora2.split('-')

var1 = hora1array[0]
var2 = hora1array[1]
var3 = hora2array[0] 
var4 = hora2array[1]
    
08.06.2018 / 23:12