Reputation: 4505
I am trying to find a way to use a wildcard in an if statement. So I have values like this: 07/22/2012 (dates) and I then want it to do:
if (date = "07/" *) { alert("test"); };
it must also only use the wildcard after the 07 as in the middle it can have: 06/07/2012
Any advice appreicated, thanks simon. Also I can use jquery if anyone knows a easier way in that.
Upvotes: 1
Views: 6679
Reputation: 5822
Can I recommend that if you are trying to manipulate dates you use a library like moment.js.
For example to check that a date's month is July do:
// month starts at 0 so July => 6
var month = 6;
var d = moment("07/22/2012", "MM-DD-YYYY");
if( d.month() === month ) alert("test");
Example here
Upvotes: 0
Reputation: 179176
If you need to match a string to a particular pattern, you should use regular expressions.
If you want to test that a string begins with a certain substring, you'd use a RegExp such as:
/^07\//
/
at the beginning and end delimit a Regular Expression literal^
matches the beginning of the string, it prevents the pattern from matching within the date, such as '06/07/08'
07
matches the string '07'
\/
matches a /
character, the \
character is used as an escape so that the regex isn't closed, similar to how quotes within a string need to be escaped with \
(e.x. "\""
).The way to check in an if
statement would be to use the test
method:
if (/^07\//.test(yourDate)) {
...do stuff...
}
This is all unicorns and rainbows for pattern matching strings, but if you're working with dates a lot, you should be parsing the date into a Date
object and managing it through an object, rather than trying to perform complex pattern matching.
Upvotes: 0
Reputation: 665030
if (date.substr(0, 3) == "07/")
to check whether the string begins with that sequence. In very modern JS engines you can also use date.startsWith("07/")
(also when you shim it).
For more complex matching, you might want to use a regular expression. "beginswith" would look like this:
/^07\//.test(date)
Upvotes: 0
Reputation: 134227
You can use the substring
function to check that particular part of the string:
if (date.substring(0, 3) === "07/") { alert("test"); };
That said, I agree there may be bigger problems with your use case. If you are trying to verify dates you really should be using date functions instead of trying to validate strings.
Upvotes: 3