I have an array of object that I need to iterate through. I'm trying to check that is contain the following string date : "7/2/2019 - 7/31/2019".
My issue is that my regex is not working :
const dateType = /(\d{4})([\/-])(\d{1,2})\2(\d{1,2})/;
I tried to filter trough this array of objects and check with a regex that current object.name string contain said string date but as before, my regex is problematic.
const isMatch = this.state.selectedFilters.filter((filter) =>
dateType.test(filter.name));
if (isMatch) {
// ...
}
How to make my regex match this format of dates : "7/2/2019 - 7/31/2019"?
Thanks in advance for your help.
Try this:
((0?[1-9])|(1[0-2]))\/((0?[1-9])|([12][0-9])|(3[01]))\/((\d{4})|(\d{2}))\s*-\s*((0?[1-9])|(1[0-2]))\/((0?[1-9])|([12][0-9])|(3[01]))\/((\d{4})|(\d{2}))
Here Is Demo
Here is a regex that will work : ^(((0)[0-9])|((1)[0-2]))(\/)([0-2][0-9]|(3)[0-1])(\/)\d{4} - (((0)[0-9])|((1)[0-2]))(\/)([0-2][0-9]|(3)[0-1])(\/)\d{4}$
The format is mm/dd/yyy - mm/dd/yyy.
You can use moment library to determine whether this date range is valid or not.
For example:
let dateRange = "7/2/2019 - 7/31/2019";
let start = dateRange.split('-')[0];
let end = dateRange.split('-')[1];
moment(start).isValid(); // true
moment(end).isValid(); // true
you can combine it with your desired date format like so:
moment('17/23/2019').format("M/D/YYYY"); // print invalid date
Related
I have this object "FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020" and need to extract the FROM_DATE value 2/9/2020. I am trying to use replace, to replace everything before and after the from date with an empty string, but I'm not sure how to get both sides of the value.
at the moment I can remove everything up until the date value with this... /.*FROM_DATE":"/ but how can I now remove the final part of the object?
Thanks
If you need to make it with replace, just use:
const input = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
const date = input.replace(/^.*"FROM_DATE":"([\d/]+)".*$/, '$1');
Now you can use date with just the date in it...
In a second time you could remove /",.*/, but this seems too much heuristic to me.
You'd better just catch the first capturing group from the following regex:
/FROM_DATE":"([0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9][0-9][0-9])"/
let str = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
let pattern = /FROM_DATE":"([0-9][0-9]?\/[0-9][0-9]?\/[0-9][0-9][0-9][0-9])"/
alert(str.match(pattern)[1]);
Your sample string looks very much like JSON. So much so in fact that you could just wrap it in braces, parse it as and object, and get the value of the FROM_DATE.
EG:
function almostJsonStringToObject(str) {
return JSON.parse('{' + str + '}');
}
var str = '"FILTER_DATE":"LAST_MONTH", "FROM_DATE":"2/9/2020", "TO_DATE":"3/9/2020"';
var obj = almostJsonStringToObject(str);
var fromdate = obj.FROM_DATE;
console.log(fromdate);
I'm trying to insert events into a calendar. the problem is my events are structured like this: xx/xx/xxxx and the calendar uses another format
xx-xx-xxxx. How do I make this transformation ?
I have transformed the dates from JSON format to a string but I can't change the / into -.
data.forEach(function (element) {
let date = new Date(element.sessionDate)
datesArr.push(date.toLocaleDateString())
})
console.log(datesArr)
And now my array looks like this:
0: "12/24/2018"
1: "12/27/2018"
2: "1/3/2019"
3: "1/3/2019"
4: "1/7/2019"
My expected result for the calendar to receive the events should be: ['2019-03-04', '2019-03-08', '2019-03-12', '2019-03-15'].
There are a couple of ways to do this:
The array version
You could replace them using a regex and then glue matched values back together.
const input = '12/24/2018';
const parts = input.split('/');
const output = `${parts[2]}-${parts[0]}-${parts[1]}`;
console.log(new Date(output));
The regex version
You could replace them using a regex and then glue matched values back together.
const input = '12/24/2018';
const output = input.replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})/, '$3-$1-$2');
console.log(new Date(output));
Or using a library like moment.js
Split the string value by "/" separation gives an array of results. Then join the array with "-" to get the string result back. Use Array.map() to transform into a new array.
const dates = ['2019/03/04', '2019/03/08', '2019/03/12', '2019/03/15'];
const formattedDates = dates.map( date => date.split("/").join("-"));
console.log(formattedDates); //["2019-03-04", "2019-03-08", "2019-03-12", "2019-03-15"]
Hi i am try to find a variable date in a string with a regex and after this i want to save the date in a new variable my code looks like:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
if(valide.test(text) === true){
}
how can i put the found date (02.02.1989) in a new variable
You can create groups in your Regex expression (just put the values you want between parenthesis) and then use this to get the specific group value.
Note, however, I think your regex is wrong... it seems you end with 1 plus 4 digits
You can use match on a string:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
console.dir(text.match(valide)) // ["02.02.1989"]
if(valide.test(text) === true){
}
Using REGEXP function match you can extract the part that match your regular expression.
After this you will get an object. In this case i turn it into a string so you can do a lot more things with it.
var myDate = text.match(valide).toString();
Hope this helps :>
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
if(valide.test(text) === true){
var myDate = text.match(valide).toString();
console.log(myDate)
}
You can use match for that:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
var foundDate = text.match(valide);
console.log(foundDate);
Also, you can make the regex a bit simpler if you switch the ([./-]) to ([-.]), because - is considered a literal match if it comes first inside a character class.
You could do something like this.
var result = text.match(valide)
Here is a reference for the match method String.prototype.match
I've a string something like
<dt>Source:</dt>
<dd>
Emergence: Title; 2005, Vol. 9 Issue 30, p120-203, 12p
</dd>
Now I am a regex to fetch different values for it, i.e. : Volume, issue, date etc
so, I fetch entire text using :
var attr = jQuery("dl dt:contains('Source:') ~ dd:eq(0)").text();
And use regex to fetch different values, such as :
To fetch start page I use, following regex:
var regex = new RegExp("p\\d+(?=[-\\s]{1})");
var regexValPS = attr.match(regex);
Return value : p120, expected : 120
Similarly, to fetch Volume info, I use following, regex:
var regexVol = new RegExp("Vol.\\s\\d+");
var regexValVol = attributeVal.match(regexVol);
I get : Vol. 9 , I want : 9
Similarly I am getting issue number with "Issue" text :
var regEx = new RegExp("Issue\\s\\d+");
var regExVal = attributeVal.match(regEx);
I Should get : 30 instead : Issue 30
The problem is I can't use another regex to get the desired value, can't strip/parseInt etc, and the pattern must be able to fetch information in a single regex.
Use grouping (...) and read its match ยป
Demo:
var str = "Emergence: Title; 2005, Vol. 9 Issue 30, p120-203, 12p";
var re = /p(\d+)(?=[\-\s])/;
document.writeln(re.exec(str)[1]); // prints: 120
re = /Vol\.\s(\d+)/;
document.writeln(re.exec(str)[1]); // prints: 9
Test it here.
Toget the desired info using a single regex, you need to take advantage of regex grouping:
var regEx = new RegExp("Issue\\s(\\d+)");
var regExVal = attributeVal.match(regEx)[1];
If you cannot modify the regex, you can maybe parse the resulting number :
var number = "Issue 30".replace(/\D/g, '');
If I understand you correctly, you do not want to do further parsing on the string values returned by the .match() calls, but can accept a different regular expression if it returns the necessary values in one statement.
Your regex needs a capture group () to retrieve the desired numbers, and place them in an array index [] (the first index [0] will hold the entire matched string, and subsequent indices hold the () captured substrings).
Instead of new RegExp() you can use the simpler /pattern/ regex literal in this case, and it is possible to extract the desired value in a single statement for all cases.
var yourString = '<dt>Source:</dt>\
<dd>\
Emergence: Title; 2005, Vol. 9 Issue 30, p120-203, 12p\
</dd>';
// Match the page, captured in index [1]
yourString.match(/p(\d+)(?=[-\s]{1})/)[1];
// "120"
// Match the Vol captured in index [1]
yourString.match(/Vol\.\s(\d+)/)[1];
// "9"
// Match the issue captured in index [1]
yourString.match(/Issue\s(\d+)/)[1];
// "30"
Here it is on jsfiddle
Try this:
var attr = jQuery("dt:contains('Source:') ~ dd:eq(0)").text();
console.log(attr);
console.log(attr.match(/p(\d+)(?=[-\s]{1})/)[1]);
console.log(attr.match(/Vol\.\s(\d+)/)[1]);
console.log(attr.match(/Issue\s(\d+)/)[1]);
For more details: JQUERY REGEX EXAMPLES TO USE WITH .MATCH().
how to split an array index i.e.. sample code
var parts = currentVal.split(" ");
var datePart = parts.splice(0,1);
alert("Date: " + datePart );
var timePart = parts.join(' ');
here i am validating the date time regular expression. var datePart is an array index, now i want to split datepart ....
var parts1 = datePart.split('/');
parts1.date = parseInt(parts1[0]);
parts1.month = parseInt(parts1[1]);
parts1.year = parseInt(parts1[2]);
but it is showing uncaught type error, their is no method split(); Can any one help me how do i separate date, month, year.
If you're trying to just check whether a string represents a valid date or not, I would personally recommend the magical Date object that javascript natively supports. Through some sort of wizardry it can read the date in almost any format you throw at it, and if it is an invalid date it will evaluate to the string Invalid Date.
So to check if currentVal is a valid date, do:
if (new Date(currentVal) == 'Invalid Date') {
... // The date is invalid
} else {
... // The date is valid
}
On the other hand, if you need to use a specific regex to validate the date, you could either do something like
var parts = currentVal.split(' ');
var dateParts = parts[0].split('/');
var timePart = parts[1]; // Maybe you want to split this as well?
And this would leave dateParts as an array containing the month, day and year.
I think you are looking for the function explode().
http://php.net/manual/en/function.explode.php
Actually function splice returns an array of removed elements, so to solve you problem you just need to apply split on the first element of datePart array:
var parts1 = datePart[0].split("/");