一.JavaScript实现
function acctNoFormat(acctNo = '', mask = true) { const val = acctNo.toString(); if (mask && acctNo.length > 10) { const res = `${val.substr(0, 4)}****${val.substr(-5)}`; return this.acctNoFormat(res, false); } return val.replace(/(S{4})/g, '$1 ').replace(/s*$/, ''); }
测试验证:
二.Java实现
package com.test; public class MaskTest { public static void main(String[] args) { MaskTest maskTest = new MaskTest(); System.out.println(maskTest.acctNoFormat("9999602770340150000339")); System.out.println(maskTest.acctNoFormat("999900339")); } private String acctNoFormat(String acctNo) { if(acctNo.trim().length() > 9) { return acctNo.replaceAll("(\S{4})\S*(\S{5})", "$1****$2").replaceAll("(\S{4})", "$1 "); } return acctNo.trim().replaceAll("(\S{4})", "$1 "); } }
测试验证: