how to take the initial and final schedules and store in two variables with javascript?

Asked

Viewed 48 times

0

how to take initial and final schedules and store in two variables with javascript?

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

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

using substring could not because they vary dynamically..

  • Daywison, pay attention to your questions. Looking at your history, you have many unresolved questions with multiple answers, and you keep asking questions without solving the previous ones. This is not good. Value users who spend time answering their questions. Choose an answer and mark . Or if no answer solved the problem, ask who answered to find the solution. Abs!

3 answers

1

You can do it this way with while by checking whether the variables hora exist and creating the variables var 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 an overall scope.

If it’s just these two variables (hora1 and hora2), can do so:

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

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'

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]
  • Only one parseint (hora1array[0]) was missing. This function will eat everything that is not number, that is, the "h" and the white spaces that were in the split

Browser other questions tagged

You are not signed in. Login or sign up in order to post.