how to extract time format from string using regex - javascript

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!

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.

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

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)

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

Related

momentjs get localized format with month and days only

When used with .format('ll') I get a year, suffix, how can I fix the above to remove it?
E.g.: Jan 29, 2018 -> Jan 29
I try to use regular to replace, but it is quite complicated.
moment().format('ll').replace(new RegExp('[^\.]?' + moment().format('YYYY') + '.?'), '')
Jan 29, 2018 -> Jan 29,
reference: https://github.com/moment/moment/issues/3341
moment().format('ll')
.replace(moment().format('YYYY'), '') // remove year
.replace(/\s\s+/g, ' ')// remove double spaces, if any
.trim() // remove spaces from the start and the end
.replace(/[рг]\./, '') // remove year letter from RU/UK locales
.replace(/de$/, '') // remove year prefix from PT
.replace(/b\.$/, '') // remove year prefix from SE
.trim() // remove spaces from the start and the end
.replace(/,$/g, '')
Thanks: Localizing day and month in moment.js
How about using Javascript split :
console.log(moment().format('ll').split(',')[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
To remove the year and comma from the date string formatted with ll in moment.js, you can use the moment().format('MMM D') method, which will format the date in the format "MMM D" (e.g. "Jan 29"). Here's an example:
const moment = require('moment');
const date = moment().format('ll');
const formattedDate = moment(date, 'll').format('MMM D');
console.log(formattedDate); // Outputs e.g. "Feb 18"
In this example, we first format the date string using ll, and then use the format method with the MMM D format to extract only the month and day. The resulting string will not include the year or comma.
Alternatively, you can use the replace method with a regular expression to remove the year and comma from the date string:
const moment = require('moment');
const date = moment().format('ll');
const formattedDate = date.replace(/, \d{4}/, '');
console.log(formattedDate); // Outputs e.g. "Feb 18"
In this example, we use the replace method with a regular expression that matches a comma followed by a space and a four-digit year, and replace it with an empty string. This will remove the year and comma from the date string, leaving only the month and day.

How to split Suffix from a number using jquery?

How can I convert this: NIFTY 16th JAN 12300 CE into NIFTY 16<sup>th</sup> JAN 12300 CE using jQuery?
To achieve this you can use a regular expression. To help negate the possibility of a false positive when the target string occurs within a word you can have the regex look specifically for the st, nd, rd or th strings when they follow an integer of 1 or 2 characters in length. Try this:
["NIFTY 16th JAN 12300 CE", "rd ND 21st April"].forEach(v => {
let output = v.replace(/(\d{1,2})(st|nd|rd|th)/gi, '$1<sup>$2</sup>');
console.log(output);
});
You can split th and rejoin with <sup>th</sup>
var x = "NIFTY 16th JAN 12300 CE";
var y = x.split("th").join("<sup>th</sup>");
console.log(y);
Here is the working code for the given requirement.
It works by identifying the day number, day suffix and replacing the pattern with required one.
var input = "NIFTY 16th JAN 12300 CE";
// Get the day string (Examples: 16th / 3rd)
var dayString = input.match(/[0-9]+[a-zA-Z]+/g);
// Get the day-number and day-suffix
var dayNumber = dayString.toString().match(/[0-9]+/i);
var daySuffix = dayString.toString().match(/[a-zA-Z]+/i);
// Print the output
console.log(dayNumber + "<sup>" + daySuffix + "</sup>");

regex For Flight no and Date

I have the following string
XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018
Want to extract the data in below format:
Flight No : XX1366,XX4515,XX3416,XX1744
Flight Date : Monday 5 November 2018, Monday 5 November 2018, Monday 17 December 2018, Tuesday 18 December 2018
My Code : A, B, C, D (which is after the Flight No)
Could you help me to extract this data using regular expression?
This may be a bit laggy but should work, you can adapt it easily :
(XX[0-9]+)([A-Z])([a-zA-Z]+ [0-9]+ [a-zA-Z]+ [0-9]+)
Pleas note that you can always test your regex online at sites like https://regexr.com/
Surely not the most elegant solution, however the following works too:
XX(\d*)(\w)(\w*\s\d+\s\w*\s\d*)
As a sidenote in case you're wondering - people on the website are far more likely to answer your question if you have put in some effort beforehand. Basically it's a forum for coding help, rather than on-demand code-writers. :)
On option could be to use 2 capturing groups to match either XX followed by 4 digits or match any character and use a positive lookahead to assert that what followed is XX followed by 4 digits or the end of the string $
Then while looping the matches collect the values in an array and use join to show them comma separated.
(XX\d{4})\*\*[A-Z]\*\*|(.*?(?=XX\d{4}|$))
Regex demo
const regex = /(XX\d{4})\*\*[A-Z]\*\*|(.*?(?=XX\d{4}|$))/g;
const str = `XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018`;
let m;
let flights = [];
let flightDates = [];
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if (m[1]) {
flights.push(m[1]);
}
if (m[2]) {
flightDates.push(m[2]);
}
}
console.log("Flight No: " + flights.join(','));
console.log("Flight Date: " + flightDates.join(', '));
Or you might use a combination of map and split to create a multidemensional array where the first value is for example XX1366 and the second Monday 5 November 2018 and you could extract those values. First split on the positive lookahead (?=XX\d{4}) and then split on matching \*\*[A-Z]\*\*
const str = `XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018`;
let res = str.split(/(?=XX\d{4})/)
.map(x => x.split(/\*\*[A-Z]\*\*/)
);
const str = `XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018`;
let res = str.split(/(?=XX\d{4})/)
.map(x => x.split(/\*\*[A-Z]\*\*/));
console.log("Flight No: " + res.map(x => x[0]).join(', '));
console.log("Flight Date: " + res.map(x => x[1]).join(', '));
I think this regex can help you :
Flight No : (XX[0-9]+)
Flight Date : [MTWFS][a-z]+ [0-9]{1,2} [a-zA-Z]+ [0-9]{4}
Code : (?<=\*)([A-Z])
You can use /y flag to match at last Index.

extract IP on large text using AppleScript / JavaScript

I'm try to selecting a large text and extract all the IP from this text.
E.g
fdsfsfsdfsd 36.23.227.234 Paris,FR FKGNGH 2df2df5cdsss 12151281250 November
23d, 2014 November 23d,
2014 titlethere 6928699 dfgdfgdfg REWG50 US$50.00
fdsfddfseed 96.8.225.128 London,UK FDGSDS ASDGSDG22GDS 33583855464 January
30d, 2011 January 30d, 2011 titlethere 34576874 dsfasdg
ASASDF41 US€0.00
the result would be 36.23.227.234 96.8.225.128
Is this possible ? as the data is very random ? can AppleScript or maybe more javascript I'm guessing can do this?
You can use regular expressions match() function in JavaScript:
var str = 'fdsfsfsdfsd 36.23.227.234 Paris,FR FKGNGH 2df2df5cdsss 12151281250 November 23d, 2014 November 23d, 2014 titlethere 6928699 dfgdfgdfg REWG50 US$50.00 fdsfddfseed 96.8.225.128 London,UK FDGSDS ASDGSDG22GDS 33583855464 January 30d, 2011 January 30d, 2011 titlethere 34576874 dsfasdg ASASDF41 US€0.00';
var regexp = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/gi;
var matches_array = str.match(regexp);
console.log(matches_array);
Which gives you Array [ "36.23.227.234", "96.8.225.128" ]
See https://stackoverflow.com/a/41610014 for all occurences of a string and https://stackoverflow.com/a/32689475 for regex to find IP addresses.

Javascript: Extract a date from a string?

I have a string formatted as either
Today 3:28AM
Yesterday 3:28AM
08/22/2011 3:28AM
What I need to do is somehow extract into a variable the date portion of my string, ie. 'Today', 'Yesterday' or a date formatted as DD/MM/YYYY.
Is something like this possible at all with Javascript?
Since the JavaScript date parser won't recognize your dates, you can write a parser that puts the date into a format that it will recognize. Here is a function that takes the date examples that you gave and formats them to get a valid date string:
function strToDate(dateStr) {
var dayTimeSplit = dateStr.split(" ");
var day = dayTimeSplit[0];
var time = dayTimeSplit[1];
if (day == "Today") {
day = new Date();
} else if (day == "Yesterday") {
day = new Date();
day.setDate(day.getDate() - 1);
} else {
day = new Date(day);
}
var hourMinutes = time.substring(0, time.length -2);
var amPM = time.substring(time.length -2, time.length);
return new Date((day.getMonth() + 1) + "/" + day.getDate() + "/" + day.getFullYear()
+ " " + hourMinutes + " " + amPM);
}
Then you can call stroToDate to convert your date formats to a valid JavaScript Date:
console.log(strToDate("Today 3:28AM"));
console.log(strToDate("Yesterday 3:28AM"));
console.log(strToDate("08/22/2011 3:28AM"));
Outputs:
Sun Sep 25 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Sat Sep 24 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Mon Aug 22 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Obviously "Today" and "Yesterday" can never be transformed back to a real numeric date, for now it seems that what are you trying to do here is to save it as "Today" and "Yesterday", right?
It appears that the dd/mm/yyyy hh:mmxx you specified is always separated by a space.
so you can just split the string into two, and save the first part as your date.
the javascript function:
http://www.w3schools.com/jsref/jsref_split.asp
As for how to transform from "Today" back to 26/09/2011 etc, you need to seek solution from the XML side.
Here is a similar question: Javascript equivalent of php's strtotime()?
Here is the linked article: http://w3schools.com/jS/js_obj_date.asp
And the suggested solution:
Basically, you can use the date constructor to parse a date
var d=new Date("October 13, 1975 11:13:00");
There are a couple of ways you could do this. I will offer 2 of them.
option1:
If the day always at the beginning of the string you could capture the the first part by using a regular expression like /([a-z0-9]*)\s|([0-9]{1,})\/([0-9]{1,})\/([0-9]{1,})\s/ <- im not the best regex writer.
option2:
You could also do a positive look ahead if the time come immediately after the day (like your example above. Here is a link with the proper syntax for JS regex. http://www.javascriptkit.com/javatutors/redev2.shtml you can scroll down to lookaheads and see an example that should get you suared away there.
var reTYD = /(today|yesterday|\d{1,2}\/\d{1,2}\/\d{4})/i;
console.log( myString.match(reTYD) );

Categories