Makop
Makop

Reputation: 35

how to extract time format from string using regex

I want to extract time from this string "Last Updated on Jul 9 2019, 3:15 pm +08"

<div id="demo"></div>
<script>
var str = "Last Updated on Jul 9 2019, 3:15 pm +08";

  var result = str.match(???);
    if(result) {
       document.getElementById("demo").innerHTML = result;
    }
</script>

or is it possible to extract the date and time but in array form like ['Jul 9 2019','3:15pm']

I'm new to using regular expression and have no idea how to formulate the pattern. Thanks in advance!

Upvotes: 1

Views: 306

Answers (4)

Kobe
Kobe

Reputation: 6446

You can use a positive lookbehind to find 'on' in the string, grab everything up to the pm/am, and split on the comma and space, assuming the format is consistent:

const str = "Last Updated on Jul 9 2019, 3:15 pm +08"
console.log(str.match(/(?<=on ).*(p|a)m/)[0].split(', '))

Note, the positive lookbehind feature is not compatible with all browsers, so I would recommend using adiga's approach if compatibility is an issue.

Upvotes: 1

adiga
adiga

Reputation: 35222

You could use the regex /on ([^,]+),\s*(.*(?:am|pm))/ with one capturing for date and another for time

var str = "Last Updated on Jul 9 2019, 3:15 pm +08";
var result = str.match(/on ([^,]+),\s*(.*(?:am|pm))/);
result.shift();

console.log(result)

Regex demo

Upvotes: 1

simona
simona

Reputation: 15

if you what use regular expression you can use '\d{1,2}:\d{2} (am|pm)' for find the time into the string of date. With \d{1,2} you have the digit between 1 and 60, with (am|pm) you find string 'am' OR string 'pm'.

Upvotes: -1

Devashish
Devashish

Reputation: 1290

This can be done without using regex (assuming that the format of the time remains same like in the example you gave). Like this:

var str = "Last Updated on Jul 9 2019, 3:15 pm +08";
var onlyTime = []
onlyTime.push(str.split(' ').slice(3,6).join(' ').slice(0, -1));
onlyTime.push(str.split(' ').slice(6,8).join(''));
console.log(onlyTime)

Upvotes: 0

Related Questions