实现银行卡号每4位添加"-"符号分割

2025-10-16 17:51:41

1、实现输入框实时输入卡号,每4位自动添加"-"符号进行分割,效果图如下:

实现银行卡号每4位添加

2、Java代码实现:

public static void main(String[] args) {

 

        String l = "12222";

 

        int num;

 

        if (l.length() % 4 == 0) {

 

            num = l.length() / 4 ;

 

        } else {

 

            num = l.length() / 4 +1;

 

        }

 

        String s = "";

 

        for (int i = 0; i < num; i++) {

 

           if(l.length() % 4 == 0) {

 

               s += l.substring(4*i, (4 * (i + 1)));

 

               s+= "-";

 

           }else {

 

               if(i!=num-1){

 

                   s += l.substring(4*i, (4 * (i + 1)));

 

                   s+= "-";

 

               }

 

               if(i==num-1 ){

 

                   s += l.substring(4*(i));

 

                   s+= "-";

 

               }

 

           }

 

        }

 

        if (s.substring(s.length()-1).equals("-")) {

 

            s =  s.substring(0, s.length()-1);

 

        }

 

        System.out.println(s);

 

    }

3、JS方法实现:

//卡号处理方式-输入框input()方法

function ChangeMethod(aObject){

   var yAuthorAccNo = aObject.value;

   if(yAuthorAccNo==null || yAuthorAccNo==""){

       var yAuthorAccNo = aObject;

   }

   if(yAuthorAccNo!="" && yAuthorAccNo.indexOf("-")>-1 ){

       var AuthorAccNo = yAuthorAccNo.replace(new RegExp("-","gm"),"");

   }else {

       var AuthorAccNo = yAuthorAccNo;

   }

   var num;

   if (AuthorAccNo.length % 4 == 0) {

       num = parseInt(AuthorAccNo.length / 4) ;

   } else {

       num = parseInt(AuthorAccNo.length / 4) +1;

   }

   var sAuthorAccNo = "";

   for (var i = 0; i < num; i++) {

       if(AuthorAccNo.length % 4 == 0) {

           sAuthorAccNo += AuthorAccNo.substring(4*i, (4 * (i + 1)));

           sAuthorAccNo+= "-";

       }else {

           if(i!=num-1){

               sAuthorAccNo += AuthorAccNo.substring(4*i, (4 * (i + 1)));

               sAuthorAccNo+= "-";

           }

           if(i==num-1 ){

               sAuthorAccNo += AuthorAccNo.substring(4*(i));

               sAuthorAccNo+= "-";

           }

       }

   }

   if (sAuthorAccNo.substring(sAuthorAccNo.length-1)=="-") {

       sAuthorAccNo =  sAuthorAccNo.substring(0, sAuthorAccNo.length-1);

   }

   fm.AuthorAccNo.value=sAuthorAccNo;

}

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢