簡體   English   中英

使用javascript只顯示銀行賬戶的最后4位數字

[英]show only last 4 digits in bank account using javascript

我需要 Javascript 方面的幫助。 我需要替換包含銀行帳號的文本字段的最后 4 位數字之前的許多字符。 我已經在網上搜索過這個,但找不到一個有效的代碼。 我確實在stackoverflow上找到了一個關於信用卡的代碼,

new String('x', creditCard.Length - 4) + creditCard.Substring(creditCard.Length - 4);

我只是用 accounNumObject 替換了信用卡:

var accounNumObject = document.getElementById("bankAcctNum")

輸入非常簡單。

<cfinput type="text" name="bankAcctNum" id="bankAcctNum" maxlength="25" size="25" value="#value#" onblur="hideAccountNum();">

有人可以幫忙嗎?

除了 JavaScript 中的最后四個字符之外,要用x替換字符串,您可以使用(假設str保存字符串)...

var trailingCharsIntactCount = 4;

str = new Array(str.length - trailingCharsIntactCount + 1).join('x')
       + str.slice(-trailingCharsIntactCount);

js小提琴

您也可以使用正則表達式...

str = str.replace(/.(?=.{4})/g, 'x');

如果要從變量中添加4 ,請使用RegExp構造函數構造正則RegExp

js小提琴

如果你有幸得到支持,也...

const trailingCharsIntactCount = 4;

str = 'x'.repeat(str.length - trailingCharsIntactCount)
        + str.slice(-trailingCharsIntactCount);

String.prototype.repeat() Polyfill 可用

這是一個小提琴,顯示了您的要求:

http://jsfiddle.net/eGFqM/1/

<input id='account' value='abcdefghijklmnop'/>
<br/>
<input id='account_changed'/>
var account = document.getElementById('account');
var changed = document.getElementById('account_changed');

changed.value = new Array(account.value.length-3).join('x') + 
    account.value.substr(account.value.length-4, 4);

編輯:更新小提琴以糾正亞歷克斯指出的一個問題

同意上述所有解決方案。我只是有另一種方法。

 const maskAccountId = (accountId) => { if (accountId) { /** Condition will only executes if accountId is *not* undefined, null, empty, false or 0*/ const accountIdlength = accountId.length; const maskedLength = accountIdlength - 4; /** Modify the length as per your wish */ let newString = accountId; for (let i = 0; i < accountIdlength; i++) { if (i < maskedLength) { newString = newString.replace(accountId[i], '*'); } } return newString; } else return /**Will handle if no string is passed */ } console.log(maskAccountId('egrgrgry565yffvfdfdfdfdfgrtrt4t4'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM