change string new date to date - javascript

I have string date like
'new Date(0,0,0,11,13,16)'
and want to change it to
new Date(0,0,0,11,13,16)
anyone have an idea on it.
thanks

var str = 'new Date(0,0,0,11,13,16)';
var str1 = str.match(/\(.*\)/g)[0];
str1 = str1.replace('(', '');
str1 = str1.replace(')', '');
var dateArr = str1.split(',');
var updatedDate = new
Date(dateArr[0],dateArr[1],dateArr[2],dateArr[3],dateArr[4],dateArr[5]);
console.log(updatedDate);

Use regex to solve this problem by matching only numbers. match will return an array of numbers so use the spread operator to set all the parameters to Date.
const res = new Date(...'new Date(0,0,0,11,13,16)'.match(/[0-9]+/g));
console.log(res);

Theoretically you could use the eval function for that.
Depending on the use, this does propose some security risk though. Read more about this here
If it's possible I would suggest you use another form of date string, e.g. "yyyy-mm-dd" (2019-02-17) and parse it to a date object using the new Date(dateString) constructor (new Date('2019-01-17')).

Related

Javascript using regular expression to get date in middle of object

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

search a regex and filter it

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

How can I replace a specific part of a string?

The string looks like 2017-08-01T00:00:00.000Z
I want to keep the date 2017-08-01, I would prevent to work with replaceAT!
date.replace(date.substr(date.indexOf("T00")),"");
// I also tried RegExp like +"/g"
var d = new Date('2017-08-01T00:00:00.000Z');
d.getFullYear(); // 2017
d.getMonth() + 1; // 8
d.getDate(); // 1
What about this
"2017-08-01T00:00:00.000Z".split("T00")[0]
Use regex expression /T.*$/ - see demo below:
console.log("2017-08-01T00:00:00.000Z".replace(/T.*$/,''));
Why not just use substring()?
var date = date.substring(0,10)
If i understand you correct, a way like this should be right...
var str = '2017-08-01T00:00:00.000Z';
alert(str.substr(0, 10));
If you only want the first part of the string, you can use slice, substr or substring:
var date = "2017-08-01T00:00:00.000Z";
var part = date.slice(0,10);
// or date.substr(0,10);
// or date.substring(0,10);

Problems in replacing symbol to nothing

How can I solve this error, which i keep getting, here it is:
TypeError: date.replace is not a function
date = date.replace("*", "");
And this is all code:
var date = cellElement.innerHTML.split("/");
date = date.replace("*", "");
alert(date);
cellElement.innerHTML looks like this
2015/Rgs/01*
Something is wrong with that replace.
How can I solve it?
Because date is an array, you cannot use string methods on it. When you use split() on string, array is returned.
To replace * symbol from string, you need to first replace it and then split it by /.
var date = cellElement.innerHTML.replace("*", "").split("/");
alert(date);
You are using the wrong type of variable.
method replace works only with type String.
try this:
var date = cellElement.innerHTML.split("/");
var date2string = date.toString();
date = date2string.replace("*", "");
or:
var date = cellElement.innerHTML.replace("*","");
var result = date.split("/");
alert(result);

How to split an array index

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

Categories