David542
David542

Reputation: 110380

Javascript regular expression for year

I am pretty new to javascript. How would I find if a piece of text contains a four digit year?

For example:

var copyright = $('#copyright').val();
if \d{4} in copyright:
    do something

Upvotes: 0

Views: 2769

Answers (2)

alex
alex

Reputation: 490433

Something like this should do it...

var isValidYear = /\d{4}/.test(str);

It looks like this is user input, so you might want to trim the string before you try to validate it with this regex. Alternatively, add a \s* to either side between the start and end anchors, and it will be close enough to trim()/$.trim() for you (it won't also kill unprintable control characters).

Alternatively, if you wanted to test if the year was a valid year (at least as valid as what JavaScript can handle), you could do...

var isValidYear = ! isNaN(new Date(str, 0, 1));

Though on my Chrome, this will assume xx is 19xx and handles dates over four decimal digits.

Upvotes: 2

David Hellsing
David Hellsing

Reputation: 108500

var copyright = $('#copyright').val();
if ( /^\d{4}$/.test(copyright) ) {
    // do something
}

Upvotes: 1

Related Questions