How can I replace a specific part of a string? - javascript

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

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

change string new date to date

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

How can I remove the leading two digits from year in Date in javascript?

How can I remove the leading two digits from the year in the format 08/07/2018 in JavaScript? I just want to display 08/07/18.
You can use String.slice.
var dateStr = '19/02/2008';
var output = dateStr.slice(0, 6) + dateStr.slice(8);
console.log(output);
If its a string you could do "1990".substr(2) else you get the year from date object and do the same thing.
Also please always share your solution always. It would be really appreciated if you share what you have done.
Here is the code to remove the first two digits:
var myString = "1990";
var newString = myString.substr(2);
//output:
//myString = 90

delete character at back

12:00:00:12
How to remove 6 character from the back? the output would be 12:00, I can't use substring to get the from the front to get the 6 char, because it can be 9:00 so it's just 4 char instead of 5.
I think #ZakariaAcharki is a better solution but if you want make it by substring try this:
str = '12:00:00:12';
str.substring(0,str.length-6);
I think better if you use split() function, and take the first and second items in splited array.
var my_string ="12:00:00:12";
var array_splited = my_string.split(':');
console.log( array_splited[0] + ':' + array_splited[1] ); //12:00
If you want it in single line, e.g :
my_string.split(':')[0] + ':' + my_string.split(':')[1];
Hope this helps.
You can determine the length and than go back 6 chars e.g.
str = '12:00:00:12'
str = str.substring(0,str.length - 6);
But you may better match with
str = '12:00:00:12'.match(/^[0-9]+:[0-9]+/)[0]
A regular expression with .match() method will do:
var str1 = '12:00:00:12';
var str2 = '9:40:00:12';
var regex = /(\d+)+:+(\d\d)/g;
var newStr1 = str1.match(regex)[0];
var newStr2 = str2.match(regex)[0];
document.querySelector('#one').textContent = JSON.stringify(newStr1);
document.querySelector('#two').textContent = JSON.stringify(newStr2);
'12:00:00:12' <pre id='one'></pre>
<hr>
'9:40:00:12' <pre id='two'></pre>
var str = "12:00:00:12";
var newStrArr = str.split(":");
newStrArr.pop();
newStrArr.pop();
newStrArr.join(":");
If the time will always be in the form (0-12):(00-59);(00-59) then you could use regex and the function .match() to get the time in the format you would like:
current_time = '12:00:00'
time_formatted = current_time.match(/\d+:\d+/)
Try using split and join.
EG 1:
var num = "12:00:00:12";
console.log(num.split(':', 2).join(':'));
EG 2:
var num = "9:00:00:12";
console.log(num.split(':', 2).join(':'));
Simple and best solution:
Use slice() function.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(function(){
var str = '12:00:00:12';
alert(str.slice(0,-6));
});
Output: 12:00
JSFiddle Demo

Regex date expression not working

I have a javascript function that does some date validation.
var regex = new RegExp(my regex expression is here);
var result = regex.test(valueToTest);
However, I've been chasing my tail for the last couple of hours because the test always returned false.
This does not work
^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\d\d$
This does not work
^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\d{2}$
This works
^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)[0-9]{2}$
The only difference between the 3 patterns is the final 2 digits. All look perfectly valid but only the 3rd one returns true.
I'm trying to understand if there is anything I've done wrong, or whether there are any issues with the browser (Firefox).
Any ideas?
What about a validation without regexps?
function validateDate(string) {
var parts = string.split("/");
var year = parseInt(parts[2]);
var month = parseInt(parts[1]) - 1;
var day = parseInt(parts[0]);
var date = new Date(year, month, day);
return date.getFullYear() === year && date.getMonth() === month && date.getDate() === day;
}
Demo
You are probably putting these regexes into a string, in which case the "\d" is being translated into a "d".
Try using double slashes: "\\d"
However, I must agree with some of the other suggestions - don't use regex for parsing dates. They aren't really well suited for the job.
For example, you expression would allow '31/02/1985' which is not a date. In particular, you run into problems with leap years (which occur every 4 years except for 3 years within a 400 year time span). Try matching that with a regex!
If you use the constructor new RegExp() you should use the string format :
Example :
var regex = new RegExp(my regex expression is here);
var result = regex.test("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)[0-9]{2}" ,"ig");
but I don't recommend you to use the constructor try to use this:
result.match(/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)[0-9]{2}$/ig);
If not what do you want do with your RegExp ?
You need to use "\\d" instead of "\d".
This repros your problem, with test data:
var regex1 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\d\d$");
var regex2 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\d{2}$");
var regex3 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)[0-9]{2}$");
document.write("<div>1: "+regex1.test("22/11/1982")+"</div>");
document.write("<div>2: "+regex2.test("22/11/1982")+"</div>");
document.write("<div>3: "+regex3.test("22/11/1982")+"</div>");
Output:
1: false
2: false
3: true
This repros the fix:
var regex1 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\\d\\d$");
var regex2 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\\d{2}$");
var regex3 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)[0-9]{2}$");
document.write("<div>1: "+regex1.test("22/11/1982")+"</div>");
document.write("<div>2: "+regex2.test("22/11/1982")+"</div>");
document.write("<div>3: "+regex3.test("22/11/1982")+"</div>");
Output:
1: true
2: true
3: true
Try escaping forward slash
Eg : ^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)\d{2}$

Categories