简体   繁体   English

函数中的Javascript开关用法

[英]Javascript Switch usage in function

Here is my javascript function which replaces "yyyy" of a date format with "yy" and replaces "yy" with "y" example 这是我的JavaScript函数,将日期格式的“ yyyy”替换为“ yy”,并将“ yy”替换为“ y”示例

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

Here is my js function 这是我的js功能

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? 是否正在尝试使用switch重新编写该函数或使其递归,是否可行?

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 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM