regex For Flight no and Date - javascript

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.

Related

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

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

Javascript- how can i extract datetime from ajax responsetext

Javascript- how can i extract datetime from this ajax responsetext:
This text was brought to you by AJAX
Your request was received at:
Sunday 11 November 2018, 02:40:00 am
I would use a regex to accomplish this. The regex:
/\w{3,6}day.*(?:am|pm)$/i
It starts by matching 3 or 4 Word chars, followed by 'day', then matches any number of any char until it reaches either 'am' or 'pm' and end of string. It uses the case inssensitive match.
How to use:
var text = 'This text was brought to you by AJAX'
+ 'Your request was received at:'
+ 'Sunday 11 November 2018, 02:40:00 am'
var dateStr = text.match(/\w{3,4}day.*(?:am|pm)$/i);
var date = new Date(dateStr);
Edit:
Changed the quantifier to {3,6} so it matches Wednesday too.

Remove all characters of a string after the fourth space

Im looking for a way to remove the fourth space, (and everything following it) from a string ,this function to be for every line list from "input text area"
Example: if i have a list "Vertically" in Input text area( i will use here days of the week just for example:
Monday February 8 2016 08:05:07 GMT-0700 (PDT)
Tuesday February 9 2016 09:07:07 GMT-0700 (PDT)
Wednesday February 10 2016 01:04:07 GMT-0700 (PDT)
Thursday February 11 2016 05:15:07 GMT-0700 (PDT)
etc
when i click button remove ,results in Output Textarea to be "Vertically" like this:
Monday February 8 2016
Tuesday February 9 2016
Wednesday February 10 2016
Thursday February 11 2016
i used this script, its work good for 1st line ,but just for first line ,i want to work for all lines. Please help me ,im trying to maked myself searching in stackoverflow but without succes ,pleas can somone modify my script or tell me what i maked wrong, thank you so much.
this is my script:
function remove_list() {
var count = 0;
var list = document.myForm.Input.value;
list = list.replace(/^((?:[^ ]* ){3}[^ ]*) [\S\s]*/, "$1");
var listvalues = new Array();
var newlist = new Array();
listvalues = list.split(/[\s,]+/).join("");
var hash = new Object();
for (var i = 0; i < listvalues.length; i++) {
if (hash[listvalues[i].toLowerCase()] != 0) {
newlist = newlist.concat(listvalues[i]);
hash[listvalues[i].toLowerCase()] = 1
} else {
count++;
}
}
document.myForm.Output.value = newlist.join("");
}
Your regular expression almost works.
If you want it to work for multiple lines, you could use the m multi-line flag so that the anchors ^/$ match the start/end of each line rather than the start/end of the string.
Here is your revised regular expression:
/^((?:[^ ]* ){3}[^ ]*) [\S\s]*?$/gm
However, you could actually simplify it to the following:
/^((?:\S+\s+){3}\S+).*$/gm
Usage:
textarea.value.replace(/^((?:\S+\s+){3}\S+).*$/gm, '$1');
Explanation:
gm - Global flag; multi-line flag
^ - Anchor asserting the start of each line
((?:\S+\s+){3}\S+) - Capturing group to match one or more non-whitespace chracters followed by one or more whitespace characters three times; then match one or more non-whitespace characters again until the forth whitespace character
.* - Match the remaining characters on the line
$ - Anchor asserting the end of each line.
Here is an example demonstrating this:
var textarea = document.querySelector('textarea');
var replacedValue = textarea.value.replace(/^((?:\S+\s+){3}\S+).*$/gm, '$1');
document.getElementById('output').textContent = replacedValue;
<textarea>
Monday February 8 2016 08:05:07 GMT-0700 (PDT)
Tuesday February 9 2016 09:07:07 GMT-0700 (PDT)
Wednesday February 10 2016 01:04:07 GMT-0700 (PDT)
Thursday February 11 2016 05:15:07 GMT-0700 (PDT)
</textarea>
<p>Output:</p>
<pre id="output"></pre>
You are making that way more complicated with regex than you need to. All you really need to do is split the whole thing on new lines, loop through those, split on spaces, and then rejoin a spliced version.
function removeExtra() {
var ta = document.getElementById('lines'),
lines = ta.innerHTML,
reformatted = [];
lines = lines.split("\n");
for(var i = 0; i < lines.length; i++){
var parts = lines[i].split(" ");
reformatted.push( parts.splice(0, 4).join(" ") );
}
ta.innerHTML = reformatted.join("\n");
}
full fiddle at https://jsfiddle.net/w7z88vjv/

I am trying to validate a date with a regular expression in JavaScript but it is not working correctly?

I am trying to validate a simple date with JavaScript but my no matter what date I enter it comes up false.. I am sure I am probably doing something stupid but I cannot find the solution.
<script type="text/javascript">
/* <![CDATA[ */
function validateDate(date) {
var dateCheck = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
if (dateCheck.test(date) == false) {
window.alert("Please enter a correct date");
}
else {
window.alert("The date was entered correctly!");
}
}
/* ]]> */
</script>
Please enter a date:
input type='text' name='date' id='date'>
input type='button' name="submitDate" id='submitDate' value='Submit' onclick="validateDate()">
Your regex seems to work well.
However, you have forgotten the date parameter in the function declaration, it may be the issue.
function validateDate(date) {
...
}
Oh ok, I see that you edited your question, I understand better.
When you give a name attribute to an input element, you make a reference to this element.
So if you want to use the value of the input named date, you have to use date.value.
I've made a jsFiddle with your code and using date.value : http://jsfiddle.net/BssTY/
I've tested it on this jsFiddle as well as the regular expression itself on rubular.com, both are working with dates in the format "xx-xx-xxxx". It is failing when you're trying to use a format such as "xx-xx-xx".
Example code:
var dateCheck = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
if (dateCheck.test("02-03-2013") == false) {
window.alert("Please enter a correct date");
} else {
window.alert("The date was entered correctly!");
}
What exactly formats are you trying to check? Maybe you want to have a look at XDate which provides a pretty good JavaScript library for handling dates (you can check with the .valid method if a date is valid).
You can add more details to limit the inputs further:
^(([1-9]|[0][0-9]|[1-2][0-9]|[3][0-1])(\/|\-)([1-9]|[0][1-9]|[1][0-2])(\/|\-)([1-9]{1}[0-9]{3}|[0-9]{2}))$
See http://rubular.com/r/uTJ55LKzMK
Breakdown the regex for checking days in the month:
([1-9]|[0][0-9]|[1-2][0-9]|[3][0-1])
- Single digit, eg. 1 or 2 or 3 up to 9
- OR, can be double digits leading with 0, eg. 01 or 02 or 03 up to 09
- OR, can be double digits leading with 1 or 2, eg. 10 or 11 or 22 or 23 up to 29
- OR, can be double digits leading with 3, eg. 30 or 31
Regex for checking month:
([1-9]|[0][1-9]|[1][0-2])
- Single digit, eg. 1 or 2 or 3 up to 9
- OR, can be double digits leading with 0, eg. 01 or 02 or 03 up to 09
- OR, can be double digits leading with 1, eg. 10 or 11 or 12
Regex for checking year:
([1-9]{1}[0-9]{3}|[0-9]{2})
- Four digits leading with # in range [1-9], eg. 1001 or 1100, up to 9999
- OR, can be double digits leading with # in range [0-9], eg. 00 or 01 up to 99
There's more to validating a date than just checking the format. The OP function thinks "30-02-2013" is OK. One way to test the string is to create a date object and check against the original, e.g.
// Format dd-mm-yyyy
function validateDate(s) {
s = s.split('-');
var d = new Date(s[2], --s[1], s[0]);
return !!d && d.getMonth() == s[1] && d.getDate() == s[0];
}
validateDate('30-02-2013'); // false
validateDate('29-02-2000'); // true
use simple validation like this:
validformat=/^\d{2}\/\d{2}\/\d{4}$/

Categories