PIPIONE
您可以使用正则表达式:var cardnumber = '4567 6365 7987 3783';var first4 = cardnumber.substring(0, 4);var last5 = cardnumber.substring(cardnumber.length - 5);mask = cardnumber.substring(4, cardnumber.length - 5).replace(/\d/g,"*");console.log(first4 + mask + last5);或者,如果您可以尝试以下操作:<html><head><script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script></head><body><input class="form-control" id="myinput" data-length="12" name="name"></body></html><script>let initial = 4;let maskChars = 6;let realNumber = "";$(function() { $('#myinput').keyup(function(e) {realNumber += this.value[this.value.length-1]; if (this.value.length >= initial && this.value.length <= initial + maskChars) { this.value = this.value.slice(0, -1) + '*'; } });});</script>这就是我在JS上的工作方式。想法是一样的。如果长度大于所需的数字长度,则可以将字符替换为 *。我还没有尝试过这个Java代码。欲了解更多信息,请访问此链接: https://www.javacodeexamples.com/mask-part-of-string-example-java/878package com.javacodeexamples.stringexamples;import org.apache.commons.lang3.StringUtils;public class MaskStringExample { public static void main(String[] args) throws Exception { String str = "1234567812345678"; //mask first 4 characters System.out.println( maskString(str, 0, 4, '*') ); //mask everything but last 4 digits System.out.println( maskString(str, 0, 12, '*') ); //mask everything System.out.println( maskString(str, 0, str.length(), '*') ); //mask everything but first and last 4 digits System.out.println( maskString(str, 1, 12, '*') ); } private static String maskString(String strText, int start, int end, char maskChar) throws Exception{ if(strText == null || strText.equals("")) return ""; if(start < 0) start = 0; if( end > strText.length() ) end = strText.length(); if(start > end) throw new Exception("End index cannot be greater than start index"); int maskLength = end - start; if(maskLength == 0) return strText; String strMaskString = StringUtils.repeat(maskChar, maskLength); return StringUtils.overlay(strText, strMaskString, start, end); }}