1

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"]

1
  • 1
    What if there's a 09:00 pm? Do you just need 09:00 or 21:00 instead? Commented May 11, 2021 at 1:45

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Very handy and less complex !
1

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

1 Comment

Appreciate your help
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.