0

Here is my javascript function which replaces "yyyy" of a date format with "yy" and replaces "yy" with "y" example

    validateDateFormat("dd/mm/yyyy") gives "dd/mm/yy"
    validateDateFormat("dd/mm/yy") gives "dd/mm/y"

Here is my js function

function validateDateFormat(format) { 
    var index =  format.indexOf("yyyy");    
    if(index <0 )
     {    var index =  format.indexOf("yy");    
          if(index <0 )
             return format;
          else
               return format = format.substring(0, index) + format.substring(index+1);          
     }
    else 
        return format = format.substring(0, index) + format.substring(index+2);
}

Am trying to re-write the function with switch or make it recursive, is it doable?

4
  • 2
    Have you tried the alternatives? how did that turn out? Commented May 7, 2014 at 19:38
  • Am a novice js programmer, I tried using switch but its not doing what i intended to Commented May 7, 2014 at 19:40
  • 1
    I think you can replace your entire function with return str.replace(/yy/g, 'y');: jsfiddle.net/mQQdx. There may be a few edge cases... Commented May 7, 2014 at 19:40
  • @JasonP Hmm, what a nonsense function. I guess it does. Commented May 7, 2014 at 19:42

1 Answer 1

1

I guess You want something like this?

function validateDateFormat(s)
{
    if(s.indexOf('yyyy') > -1)
      return s.replace('yyyy','yy');

    return s.replace('yy','y');
}

alert(validateDateFormat('dd/mm/yyyy')); // "dd/mm/yy"
alert(validateDateFormat('dd/mm/yy')); // "dd/mm/y"

Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.