I am trying to use the following regular expression to test for a valid date.
^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$
which I got from
http://regexlib.com/REDetails.aspx?regexp_id=1071
My JavaScript test code is:
var date='1/1/1965';
var re = new RegExp('^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$');
alert(re.test(date));
I keep getting "false" rather than "true" for this valid test date.
Try this:
var date='1/1/1965';
var re = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])\/(29|30)|(0?[13578]|1[02])\/31)\/(19|[2-9]\d)\d{2}|0?2\/29\/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/;
alert(re.test(date));
Your problem might be escaping of the slashes.
There are 2 ways you can insert a regexp in javascript. 1st way is just put it in forward slashes, and the second way, which is the way you are doing it is with RegExp object, which means that you then have to include the regexp string itself in the JavaScript code as a string.
And as every other string in Javascript which contains special characters like backward slashes (which your regexp does), you have to escape them with yet another backslash.
So basically just replace every backslash in your code with double backslash (\\) and you should be fine.
Just put it in forward-slashes:
var re = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)\/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/
Now, while that'll get you a regular expression to use, I have to say that this may be one of the silliest applications of a regex ever. You'd be way better off just instantiating a JavaScript "Date" object and using it's surprisingly friendly API to check what you need to check.
If you instantiate a JavaScript "Date" object with a bogus date (like Februrary 30), it'll just roll to the actual date that sort-of corresponds to the bogus date; in other words, it carries over the bogus days into the next month. Thus, if you just hold on to the month and day, and create a "Date" instance, you can know that if the month and day that the "Date" instance gives you when you ask are different from the ones you fed it, then the original date must have been unreal.
Related
I am trying to edit a DateTime string in typescript file.
The string in question is 02T13:18:43.000Z.
I want to trim the first three characters including the letter T from the beginning of a string AND also all 5 characters from the end of the string, that is Z000., including the dot character. Essentialy I want the result to look like this: 13:18:43.
From what I found the following pattern (^(.*?)T) can accomplish only the first part of the trim I require, that leaves the initial result like this: 13:18:43.000Z.
What kind of Regex pattern must I use to include the second part of the trim I have mentioned? I have tried to include the following block in the same pattern (Z000.)$ but of course it failed.
Thanks.
Any help would be appreciated.
There is no need to use regular expression in order to achieve that. You can simply use:
let value = '02T13:18:43.000Z';
let newValue = value.slice(3, -5);
console.log(newValue);
it will return 13:18:43, assumming that your string will always have the same pattern. According to the documentation slice method will substring from beginIndex to endIndex. endIndex is optional.
as I see you only need regex solution so does this pattern work?
(\d{2}:)+\d{2} or simply \d{2}:\d{2}:\d{2}
it searches much times for digit-digit-doubleDot combos and digit-digit-doubleDot at the end
the only disadvange is that it doesn't check whether say there are no minutes>59 and etc.
The main reason why I didn't include checking just because I kept in mind that you get your dates from sources where data that are stored are already valid, ex. database.
Solution
This should suffice to remove both the prefix from beginning to T and postfix from . to end:
/^.*T|\..*$/g
console.log(new Date().toISOString().replace(/^.*T|\..*$/g, ''))
See the visualization on debuggex
Explanation
The section ^.*T removes all characters up to and including the last encountered T in the string.
The section \..*$ removes all characters from the first encountered . to the end of the string.
The | in between coupled with the global g flag allows the regular expression to match both sections in the string, allowing .replace(..., '') to trim both simultaneously.
I want to get all the words, except one, from a string using JS regex match function. For example, for a string testhello123worldtestWTF, excluding the word test, the result would be helloworldWTF.
I realize that I have to do it using look-ahead functions, but I can't figiure out how exactly. I came up with the following regex (?!test)[a-zA-Z]+(?=.*test), however, it work only partially.
http://refiddle.com/refiddles/59511c2075622d324c090000
IMHO, I would try to replace the incriminated word with an empty string, no?
Lookarounds seem to be an overkill for it, you can just replace the test with nothing:
var str = 'testhello123worldtestWTF';
var res = str.replace(/test/g, '');
Plugging this into your refiddle produces the results you're looking for:
/(test)/g
It matches all occurrences of the word "test" without picking up unwanted words/letters. You can set this to whatever variable you need to hold these.
WORDS OF CAUTION
Seeing that you have no set delimiters in your inputted string, I must say that you cannot reliably exclude a specific word - to a certain extent.
For example, if you want to exclude test, this might create a problem if the input was protester or rotatestreet. You don't have clear demarcations of what a word is, thus leading you to exclude test when you might not have meant to.
On the other hand, if you just want to ignore the string test regardless, just replace test with an empty string and you are good to go.
I'm trying to use this great RegEx presented here for grabbing a video id from any youtube type url:
parse youtube video id using preg_match
// getting our youtube url from an input field.
var yt_url = $('#yt_url').val();
var regexp = new RegExp('%(?:youtube(?:-nocookie)?\\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\\.be/)([^"&?/ ]{11})%','i');
var videoId = yt_url.match( regexp ) ;
console.log('vid: '+videoId);
My console is always giving me a null videoId though. Am I incorrectly escaping something in my regexp var? I added the a second backslash to escape the single backslashes already.
Scratching my head?
% are delimiters for the PHP you got the link from, Javascript does not expect delimiters when using new RegExp(). Also, it looks like \\. should probably be replaced with \. Try:
var regexp = new RegExp('(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})','i');
Also, you can create a regular expression literally by using Javascript's /.../ delimiters, but then you'll need to escape all of your /s:
var regexp = /(?:youtube(?:-nocookie)?\.com\/(?:[^/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\\.be\/)([^"&?\/ ]{11})/i;
Documentation
Update:
A quick update to address the comment on efficiency for literal expressions (/ab+c/) vs. constructors (new RegExp("ab+c")). The documentation says:
Regular expression literals provide compilation of the regular expression when the script is loaded. When the regular expression will remain constant, use this for better performance.
And:
Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
Since your expression will always be static, I would say creating it literally (the second example) would be slightly faster since it is compiled when loaded (however, don't confuse this into thinking it won't be creating a RegExp object). This small difference is confirmed with a quick benchmark test.
I have an input field where the user enters a time in format mm:hh. The format is specified inside the field (default value 09:00) but I still want to perform a client-side check to see if the format is correct.
Since the existing client-side validation is in jQuery, I'd like to keep this in jQuery as well.
I'm mainly a PHP programmer so I need some help writing this one in an optimal manner.
I know I can check each individual character (first two = digits, third = ':', last two = digits) but is there a way to do it more elegantly, while also checking the hour count is not larger than 23 and the minute count isn't larger than 59?
In PHP I would use regular expressions, I assume there's something similar for jQuery?
Something like this makes sense to me:
([01]?[0-9]|2[0-3]):[0-5][0-9]
But I'm not too familiar with jQuery syntax so I'm not sure what to do with it.
you can use regex in JavaScript too:
http://www.w3schools.com/jsref/jsref_obj_string.asp
use
.search() - http://www.w3schools.com/jsref/jsref_search.asp
or .match() - http://www.w3schools.com/jsref/jsref_match.asp
or .replace() - http://www.w3schools.com/jsref/jsref_replace.asp
EDIT:
<script>
var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/;
var correct = ($('input').val().search(regexp) >= 0) ? true : false;
</script>
EDIT2:
here the documentation of regexpobject in javascript:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
<script>
var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/;
var correct = regexp.test($('input').val());
</script>
EDIT3:
fixed the regexp
In JavaScript, regexes are delimited by /. So you would do...
var isValidTime = /([01]?[0-9]|2[0-3]):[0-5][0-9]/.test(inputString);
Your regex seems to make sense for validating any 24H time in HH:mm format. However as I state in my comment under Andreas's answer - this will return true if any part of the string matches. To make it validate the entire string, use anchors to match the start and end of the string also eg...
var isValidTime = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(inputString);
To actually pull the matches you would need to use the string.match JS function.
Oh - and please be aware that jQuery is Javascript - it's just a library of very useful stuff! However this example contains no reference to the jQuery library.
In JavaScript you can use yourstring.match(regexp) to match a string against a regular expression.
I have very limited RegEx-experience, so I cant help you with the pattern, but if you have that set .match() should be all it takes.
A different approach, but using an extra javascript lib instead of regular expressions:
var valid = moment(timeStr, "HH:mm", true).isValid();
I guess if you already use moment.js in your project, there's no downside.
And since you didn't specifically request an answer using regular expressions, I think it's valid to mention.
I need to check whether the text contains a date part with it.
for ex: mytext_12/26/2011_11:51_AM or someText_12/26/2011_13:51_PM have a date part it returns true.
I am not too good with expressions so looking for one. the format of the date - time part is fixed.
i got a way out for it but failing for time .
var containsDate = ~str.search(/\d{1,2}\/\d{1,2}\/\d{4}/);
it checks the date part perfectly but when i am trying for the time part i am messing it up some where .
_\d{1,2}:\d{2}_(?:AM|PM) this is the part for time but i am not able to generate the final regex by combining this two.
Try,
.search(/[0-9]{2}\/[0-9]{2}\/[0-9]{4}_[0-9]{2}:[0-9]{2}_(AM|PM)/)
A good resource for regex,
MDN:Regular Expressions
Try,
.search(/\d+\/\d+\/\d{4}_\d+:\d+_(AM|PM)/)