Ask Ben: Cleaning Two Digit Years Using Javascript And Regular Expressions

Posted January 26, 2007 at 8:34 AM by Ben Nadel

Tags: Javascript / DHTML, Ask Ben

Hey Ben,

Trying to replace a date "/" character with both the character and either a string of 19 or 20, for 2 year purposes.

For example, people are accustomed to plugging in the dates into their form with mm/dd/yy format. So when they plug in 12/23/97, I'd like to replace the second instance of / with /19 preceeding the 97.

If the last two year figures begin with 0 or 1, I'd replace the "/" with "/20" preceeding the rest of the figure. i.e. 09/17/02 would become 09/17/2002.

Is there a way to replace this with regular expressions? How would that be done?

The beauty of using Regular Expressions in Javascript is that each match made by the regular expression can be passed off to a Javascript function literal. You won't see this happening in any kind of compiled language such as Java or ColdFusion, which is part of why Javascript, as an interpreted language, is so freakin' sweet-ass!

For this solution, all we have to do is write a function that takes a given date string, checks for a two digit year, check the leading character and then returns the two digits with the proper two digits pre-pended.

  • // This takes a date string that MIGHT have a two digit year
  • // as the last two digits. If it does, this function replaces
  • // the two digit year with what it *assumes* is the proper
  • // four digit year.
  • function CleanDate( strDate ){
  •  
  • // Return the cleaned date.
  • return(
  • strDate.replace(
  •  
  • // This regular expression will search for a slash
  • // followed by EXACTLY two digits at the end of
  • // this date string. The two digits are being
  • // grouped together for future referencing.
  • new RegExp( "/(\\d{2})$", "" ),
  •  
  • // We are going to pass the match made by the
  • // regular expression off to this function literal.
  • // Our arguments are as follows:
  • // $0 : The entire match found.
  • // $1 : The first group within the match.
  • function( $0, $1 ){
  •  
  • // Check to see if our first group begins with
  • // a zero or a one. If so, replace with 20 else
  • // replace with 19.
  • if ($1.match( new RegExp( "^[01]{1}", "" ) )){
  •  
  • // Replace with 20.
  • return( "/20" + $1 );
  •  
  • } else {
  •  
  • // Replace with 19.
  • return( "/19" + $1 );
  •  
  • }
  •  
  • }
  • )
  • );
  •  
  • }

Hope that helps!




Reader Comments

Jan 26, 2007 at 9:46 AM // reply »
11 Comments

Having users enter a two digit year is part of the Y2K issue. A common solution for 2 year digit data was to use a pivot formula, for the below example, I set 70 as the pivot year.

Easy enough to set the pivot base, depending on the type of question being asked, such as your birth date, and then depending on the age of your user base, lower the pivot. For me, entering in 61 would result in 2061, so I'd probably lower the pivot date a bit.

<script language="javascript">
function getPivot(year) {
if (year < 70) return (2000 + year);
if (year < 1900) return (1900 + year);
return year;
}

function getDate(){
var myDate = new Date(document.getElementById('testDate').value);
var pivotDate = new Date(getPivot(myDate.getYear()),myDate.getMonth(),myDate.getDate());
alert(pivotDate);
}

</script>
<input id="testDate" value="" onchange="getDate();" />


Jan 26, 2007 at 6:11 PM // reply »
11,238 Comments

Chris,

That's a cool little snippet of code there. Thanks!


Jan 28, 2007 at 8:41 PM // reply »
95 Comments

Ben,

your example is pretty nifty. I didn't realize that you can do the equivalent of the matchEvaulator in .NET but with Java/CF Script! Nice! On a more relevant note do deal with the issue I usually just provide a calendar widget. The one at http://www.dynarch.com/projects/calendar/ is free, full of features and customizable. I use it all the time. A quick question for you, why did you have to escape the "\" in front of the special sequence "\d" as in "\\d"?

On a side note, you never got back to me about the code snippets idea.


May 11, 2010 at 3:28 PM // reply »
2 Comments

Boyan,

"\d" matches any numeric digit (0-9) as "\\d" will match the same digits as literal text -- which is helpful when using regex to evaluate a numeric value that is of data type string.

Nice post Ben!


May 11, 2010 at 10:18 PM // reply »
11,238 Comments

@Ryan,

Good point; however, it depends on the context. In Javascript strings, "\", is actually a special characters. For example, "\n" is the new line character:

"line one \n line two"

As such, if you want to create a special characters class in a Javascript RegExp, you actually have to escape the back-slash so that it doesn't try to get evaluated as a special string character.

So, to get the digit character class, \d, in a string in Javascript, you need to escape the back slash:

"\\d"

Now, that's IF you use the new RegExp() constructor. If you use the implicit regex constructor, you don't have to:

/\d/gi

In this case (which I find much less readable), since you are outside of a string literal, there's no need to escape the back-slashes.

Sorry if that was WAY more information than anyone needed.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 19, 2013 at 2:31 PM
My Experience With AngularJS - The Super-heroic JavaScript MVW Framework
It's funny really just how well that image describes the way I would imagine most people that go with angular for some project is. I have had a similar roller-coaster ride with it as well, but not qu ... read »
May 17, 2013 at 7:42 PM
HashKeyCopier - An AngularJS Utility Class For Merging Cached And Live Data
Ben - thanks so much for posting these Angular articles and findings, they've been a huge help towards learning one of the more 'complex' JavaScript frameworks out there (IMO). I have been using Angu ... read »
May 16, 2013 at 5:01 PM
UPDATE: Parsing CSV Data Files In ColdFusion With csvToArray()
Your code was the closest thing I've found to obtaining some direction for converting ISO fields to values that CF can translate properly. Thank you for posting! ... read »
May 15, 2013 at 10:37 PM
Very Simple Pusher And ColdFusion Powered Chat
hi id making plz easy ... read »
May 15, 2013 at 6:07 PM
Making SOAP Web Service Requests With ColdFusion And CFHTTP
Ben, you once again saved my bacon at work. Thank you, thank you, thank you! ... read »
May 15, 2013 at 4:15 PM
What If All User Interface (UI) Data Came In Reports?
@Josh, Thanks! @Ben, I definitely recommend the David West book "Object Thinking" I've been quoting from. It goes deeply into the philosophy and history of OO programming. His breadth ... read »
May 15, 2013 at 11:36 AM
Ask Ben: Print Part Of A Web Page With jQuery
I found this helpfull when you need to keep (refresh) the original parent page after closing the iframe child print dialog (Hoping you're not using a form at this time so it won't submit again): On ... read »
May 14, 2013 at 7:13 PM
What If All User Interface (UI) Data Came In Reports?
@Jonah, If there's any books you'd recommend on the subject of domain modelling, I'd love to hear it. I just downloaded the free PDF of "Domain Driven Design Quickly". Figured I'd give it ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools