Code of the Day: Javascript Auto-complete date format MMDDYYYY

/**
* This function helps to autocomplete the date format MMDDYYY
* Converts M to 0M and MMD to MM0D. Ex. `1/` to `01/`, `01/1/` to `01/01/`
* Adds slash for MM and MMDD Ex. `01` to `01/`, `01/02` to `01/02/`
* Converts YY to YYYY. Ex. `01/01/01` to `01/01/2001`
*
* @param {String} str
* @return {String}
*/
var autocompleteMMDDYYYYDateFormat = function (str) {
        str = str.trim();
        var matches, year,
                looksLike_MM_slash_DD = /^(\d\d\/)?\d\d$/,
                looksLike_MM_slash_D_slash = /^(\d\d\/)?(\d\/)$/,
                looksLike_MM_slash_DD_slash_DD = /^(\d\d\/\d\d\/)(\d\d)$/;
 
        if( looksLike_MM_slash_DD.test(str) ){
                str += "/";
        }else if( looksLike_MM_slash_D_slash.test(str) ){
                str = str.replace( looksLike_MM_slash_D_slash, "$10$2");
        }else if( looksLike_MM_slash_DD_slash_DD.test(str) ){
                matches = str.match( looksLike_MM_slash_DD_slash_DD );
                year = Number( matches[2] ) < 20 ? "20" : "19";
                str = String( matches[1] ) + year + String(matches[2]);
        }
        return str;
};

Demo

(Page view Count: 776)