Remove space in a date string - javascript

I'm getting a date from a database that sometimes has spaces in the times (there isn't a way to clean up DB as I don't have control). I need to remove the spaces so I can format it to a Javascrpt date.
For example:
5 : 03 PM
As you can see, this is incorrect. I've looked at Moment.js and Regex to remove spaces around the colon, but not sure how that's done or if that's the proper way. Is there a way to remove this space?
Thanks all!

Only to delete the space around the colon, try the following; (where $1 refers to the first capture group, that is the only one (:))
a.replace(/\s*(:)\s*/, "$1");
or if you wish to simplify it further, without any capturing group;
a.replace(/\s*:\s*/, ":");

If you want to, you can actually parse that date string with Moment.js, you just need to include the spaces in your formatting string:
var time = moment('5 : 03 PM', 'h : m A');
Then you can format it however you want:
time.format('h:mmA'); // "5:30PM"
time.format('hh:mm A'); // "05:03 PM"
time.format('HH:mm'); // "17:03"

For completeness you could aviod regexp:
'5 : 03pm'.split(':')
.map(function(part) { return part.trim(); })
.join(':');

Related

Javascript regex /^(19|20)([0-9]{2})-([0-9]{2}|0[0-9]{1})-([0-9]{2}|0[0-9]{1})$/g didnt find dates as value of input

and Thanks.
I created a
/^(19|20)([0-9]{2})-([0-9]{2}|0[0-9]{1})-([0-9]{2}|0[0-9]{1})$/g
Pattern in js but didnt work in browser.
I tested Here. Working but in browser js not
Following regex should do the expected check.
\((19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))\
You should be able to write your regex as the one below.
(19|20)\d{2}-\d{2}-\d{2}
See this JS code snippet:
var date = ' 2019-04-03 ';
var regex = /(19|20)\d{2}-\d{2}-\d{2}/g;
var result = date.match(regex);
console.log(result[0]);
Depending on what string you are using to match the regex on it could be that using ^ and $ is causing you trouble. Using ^ asserts the position at the start of the line. And using $ asserts the position at the end of the line. This of course means that it won't match if your string is " 1999-01-01 " with spaces or any other text on that same line.
Be advised that if you want it to work for any year and not just 1900 up to 2099 you have to use the one below.
\d{4}-\d{2}-\d{2}
On top of this do note that this captures anything that looks like a date e.g. 2099-99-99 will still be captured but is not a valid date. If you want date validation your regex will look considerably harder, see Regex to validate date format dd/mm/yyyy for an example with leap years and the like. Depending on your use case it might be easier to let Javascript do the validation.
Thats is worked. Thanks.
var date = ' 2019-04-03 ';
var regex = /(19|20)\d{2}-\d{2}-\d{2}/g;
var result = date.match(regex);
console.log(result[0]);

Changing a string from user input

Having some troubles figuring this one out as I'm not too sure what you'd even call it.
I'm trying to take a users input and swap it around, so for example:
1 input for the date: DD MM YYYY, I want them to input it as such and then change it to YYYYDDMM server side before sending it where it needs to go.
I've tried looking at regex expressions and str replace but it doesn't appear to have an option to pull the end of a users string and place it in a different location. Any insight would be appreciated of where I could find some more help on this or what direction to go in.
You can do it with regex if you capture each part of the date string in a group, and then echo the groups back in a different order, without the spaces:
const reformatDate = dateStr => dateStr.replace(/^(\d{2}) (\d{2}) (\d{4})$/, '$3$1$2');
console.log(reformatDate('05 12 2000'));
console.log(reformatDate('10 31 2010'));
console.log(reformatDate('01 01 2018'));
With Javascript's .replace, $ followed by a number in the second parameter passed to the .replace function replaces the $# with that captured group in the regular expression. For example, $3 gets replaced with whatever was matched by the third (...).
The same sort of replacement syntax works in PHP:
function reformatDate($dateStr) {
return preg_replace('/^(\d{2}) (\d{2}) (\d{4})$/', '$3$1$2', $dateStr);
}

Specific match with "OR condition" - regex

I'm making a regex to match datetime with these formats:
d/M/yyyy
d-M-yyyy
M/d/yyyy
M-d-yyyy
dd/MM/yyyy
dd-MM-yyyy
MM/dd/yyyy
MM-dd-yyyy
...
I've tried:
var reg = /^(\d{1,4}[/\-]\d{1,2}[/\-]\d{1,4}\s(\d{1,2}:){2}\d{1,2})$/;
alert(reg.test('18/07/2016 00:00:00'));
It works fine. But the problem is: it still works with this format:
d/M-yyyy
//or
dd-MM/yyyy
I saw the index of the problem is in [/\-]. I need it's duplicate correct / OR - (only one).
My question: how can I fix it?
Use a capturing group:
^\d{1,4}([/-])\d{1,2}\1\d{1,4}\s(\d{1,2}:){2}\d{1,2}$
\1 will match the same text as what matched the 1st capturing group, which is is ([/-]).

Check dateformat with regex in JS

My question is simple but takes work. I tried lots of regex expressions to check my datetime is ok or not, but though I am sure my regex exprerssion is correct it always return to me isnotok with ALERT. Can you check my code?
validateForLongDateTime('22-03-1981')
function validateForLongDateTime(date){
var regex=new RegExp("/^\d{2}[.-/]\d{2}[.-/]\d{4}$/");
var dateOk=regex.test(date);
if(dateOk){
alert('ok');
}else{
alert('notok');
}
}
There are at least 2 issues with the regex:
It has unescaped forward slashes
The hyphen in the character classes is unescaped and forms a range (matching only . and /) that is not what is necessary here.
The "fixed" regex will look like:
/^\d{2}[.\/-]\d{2}[.\/-]\d{4}$/
See demo
However, you cannot validate dates with it since it will also match 37-67-5734.
Here is an SO post with a comprehensive regex approach that looks viable
Here is my enahanced version with a character class for the delimiter:
^(?:(?:31([\/.-])(?:0?[13578]|1[02]))\1|(?:(?:29|30)([\/.-])(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29([\/.-])0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])([\/.-])(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
Here is an SO post showing another approach using Date.parse
this way you can validate date between 1 to 31 and month 1 to 12
var regex = /^(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)\d\d$/
see this demo here https://regex101.com/r/xP1bD2/1

Regex not working in JavaScript

I am trying to make sure that the format people input is exactly this :
.match(/\d{1,2}:\d\d\s((AM)|(PM))/)
Meaning that a user could write :
12:30 AM
2:30 PM
But not :
1:2 A
1:30
PM
It needs to be first two digits, followed by a colon, than two more digits, a space, and either AM or PM. But my regex expression isn't that. What am I missing?
What exactly seems to be the problem?
> "1:2 A".match(/\d{1,2}:\d\d\s((AM)|(PM))/);
null
>"12:30 AM".match(/\d{1,2}:\d\d\s((AM)|(PM))/);
["12:30 AM", "AM", "AM", undefined]
However:
You need to ground your expression to the start (^) and end ($) of the string otherwise;
> "foo 12:30 AM foo".match(/\d{1,2}:\d\d\s((AM)|(PM))/);
["12:30 AM", "AM", "AM", undefined]
Look at RegExp.test() instead, which returns a simpler true/false rather than an array.
> /^\d{1,2}:\d\d\s((AM)|(PM))$/.test("12:30 AM");
true
A simpler expression which does the same thing could be /^\d{1,2}:\d{2} [AP]M$/
Assuming that you are checking it on single line input field (and not searching it inside a text area), you should do:
/^\d{1,2}:\d\d\s[AP]M$/
How about something like this:
.match(/([0]?[1-9]|1[0-2])(:)[0-5][0-9]?( )?(AM|PM)/)
If your problem is new line character.
You can try:
'12:30
AM'.replace(/\n/, '').match(/\d{1,2}:\d\d\s((AM)|(PM))/)
Combining the ideas of Matt, c0deNinja and my own you should end up with:
/^(0?[1-9]|1[0-2]):[0-5][0-9]\s?[AP]M$/.test(input);
I've tried your code in http://www.regular-expressions.info/javascriptexample.html and it worked.
By the way, you also need to test if the time is valid. Your code now can accept things like this 99:12 AM as if they were correct. I suggest you to use something like this.
\b(1[0-2]|\d):[0-5][0-9]\s([aApP][mM])\b
=)
Your regex seems to be right. Incorporating some ideas above, you could test your string like this with Regex:
^(1[0-2]|\d):[0-5]\d [aApP][mM]$
And the testing code in Javascript:
var regex = /^(1[0-2]|\d):[0-5]\d [aApP][mM]$/g;
var input = "2:30 PM";
if(regex.test(input)) {
var matches = input.match(regex);
for(var match in matches) {
alert(matches[match]);
}
} else {
alert("No matches found!");
}

Categories