How do you capture the hours in a String?

1

I'm making a javascript code in which I'll need to split a sentence so I search the hours, I want only the value of them and so I can separate them, to put the value separately.

Ex: 

String: 11:11 as 22:22 / 33:33 as 44:44 / 55:55 as 66:66

Saída: 11:11,22:22,,33:33,44:44,55:55,66:66

Saída 2: var1 = "11:11"; var2 = "22:22"; var3 = "33:33"; var4 = "44:44"; var5 = "55:55"; var6 = "66:66";
    
asked by anonymous 04.01.2019 / 12:00

2 answers

7

This simple regex solves your problem: /\b\d{2}:\d{2}\b/g

let texto = '11:11 as 22:22 / 33:33 as 44:44 / 55:55 as 66:66'
const expressao = /\b\d{2}:\d{2}\b/g

console.log(texto.match(expressao))
  • \b so that examples such as 123456:789 are not returned
  • \d shortcut to [0-9]
  • % with% quantifier that takes exactly two numbers.
  • {2} flag to find all possible results.

Detail : The result results in an array, so just use it the way you want!

    
04.01.2019 / 12:27
1

Follow below:

var horariosFormatoInicial = '11:11 as 22:22 / 33:33 as 44:44 / 55:55 as 66:66';
var horariosSeparados = horariosFormatoInicial.replace(/ as /g, ' / ').split(' / ');
var saida1 = horariosSeparados.join(',');
var saida2 = '';

for (var i = 0; i < horariosSeparados.length; i++) {
    saida2 += 'var' + (i + 1) + ' = "' + horariosSeparados[i] + '"; ';
}

Our variable horariosFormatoInicial contains its original string, unformatted.

Then we create the variable horariosSeparados which will be an array storing each time to use in the creation of saida1 and saida2 . In it we replace all the text strings as with / , so we will have all the times divided in the same format.

  

'11: 11 / 22:22 / 33:33 / 44:44 / 55:55 / 66:66 ';

Now we can use the function split() , passing the character / , to transform into our array.

  

[11:11, 22:22, 33:33, 44:44, 55:55, 66:66]

Now we can take our array and turn it into Output 1, using the function join() , which takes each element of the array and separates it by the character entered, which in this case is the comma.

For output 2, we use for to traverse our array and format the new string in the desired format.

    
04.01.2019 / 12:36