soccerway
soccerway

Reputation: 11931

Using regex, separate the time value in time format

Using Regex I would like to get time alone from the below text string. The below one is printing in a single line. My objective is use less .js line to achieve this. Any advise would be really helpful.

let myArr = [];
let text = "12:30 am01:00 am10:00 am10:15 am";
finalTime = text.replace(/[^0-9: ]/g, '');
console.log(finalTime);

enter image description here

I am expecting Array values should display as below for me to choose easily or may be a json object will do

let myArr = ["12:30", "01:00", "10:00", "10:15"]

Upvotes: 1

Views: 68

Answers (3)

XMehdi01
XMehdi01

Reputation: 1

Use split with delimiter am and exclude last one [''] with slicing

let text = "12:30 am01:00 am10:00 am10:15 am";
let myArr = text.split(' am').slice(0,-1);
console.log(myArr);

P.S: it works only for am times. if you want works for pm too, use another split with pm as delimiter.

Upvotes: 0

Nick
Nick

Reputation: 147146

If you want to deal with the possibility of times in the afternoon e.g. 01:00 pm, you could use matchAll and convert the resultant arrays into a string by checking for am or pm and adjusting the time as necessary:

let text = "12:30 am01:00 am10:00 pm10:15 am";

myArr = Array.from(text.matchAll(/(0[0-9]|1[012])(:[0-5][0-9])\s+([ap])m/gi),
                   m => (m[3].toLowerCase() == 'a' ? m[1] : (+m[1] + 12)) + m[2]);

console.log(myArr);

Note I've also adjusted the regex to ensure that the times are valid; if you know they will be you can replace the regex with just

(\d\d)(:\d\d)\s+([ap])m

Upvotes: 1

Barmar
Barmar

Reputation: 780787

Use match instead of replace. It will return an array of all the matches.

let text = "12:30 am01:00 am10:00 am10:15 am";
let myArr = text.match(/[0-9:]+/g);
console.log(myArr);

Upvotes: 3

Related Questions