1

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!

3
  • Your desired output of [{'Jul 9 2019'},{'3:15pm'}] is not even valid syntax in Javascript. Commented Jul 9, 2019 at 8:00
  • You can just take a sub string, if the string always starts with Last Updated on . Otherwise, there is no way of doing this with a simple regex. Commented Jul 9, 2019 at 8:02
  • sorry, it should be array object i mean Commented Jul 9, 2019 at 8:03

4 Answers 4

1

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.

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

1 Comment

No problem. If you ever need more help, feel free to ask.
1

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

4 Comments

thank you this is very useful answer same with the first one
You could use var [, ...result] here instead of shift, so you don't have to write another line :P
@Kobe Yeah but, OP is using var. So, didn't want to make it confusing by adding destructuring
Yeah, I understand, fair enough.
0

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)

Comments

-1

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'.

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.