javascript 使用javascript仅显示银行帐户中的最后4位数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9794986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
show only last 4 digits in bank account using javascript
提问by ScrumMaster Guy
I need help with Javascript. I need to replace however many characters there are previous to the last 4 digits of a text field that contains bank account number. I have searched through the net on this, but cannot find one code that works. I did find a code here on stackoverflow, which was regarding credit card,
我需要 Javascript 方面的帮助。我需要替换包含银行帐号的文本字段的最后 4 位数字之前的许多字符。我已经在网上搜索过这个,但找不到一个有效的代码。我确实在stackoverflow上找到了一个关于信用卡的代码,
new String('x', creditCard.Length - 4) + creditCard.Substring(creditCard.Length - 4);
I just replaced the creditCard with accounNumObject:
我只是用 accounNumObject 替换了信用卡:
var accounNumObject = document.getElementById("bankAcctNum")
The input is pretty simple.
输入非常简单。
<cfinput type="text" name="bankAcctNum" id="bankAcctNum" maxlength="25" size="25" value="#value#" onblur="hideAccountNum();">
Can anyone help please?
有人可以帮忙吗?
回答by alex
To replace a string with x
except for the last four characters in JavaScript, you could use (assuming str
holds the string)...
要将字符串替换x
为 JavaScript 中除最后四个字符之外的字符串,您可以使用(假设str
保存字符串)...
var trailingCharsIntactCount = 4;
str = new Array(str.length - trailingCharsIntactCount + 1).join('x')
+ str.slice(-trailingCharsIntactCount);
You could also use a regular expression...
您也可以使用正则表达式...
str = str.replace(/.(?=.{4})/g, 'x');
If you want to add the 4
from a variable, construct the regex with the RegExp
constructor.
如果要添加4
from 变量,请使用构造函数构造正则表达式RegExp
。
If you're fortunate enough to have the support, also...
如果你有幸得到支持,也...
const trailingCharsIntactCount = 4;
str = 'x'.repeat(str.length - trailingCharsIntactCount)
+ str.slice(-trailingCharsIntactCount);
Polyfill for String.prototype.repeat()
is available.
Polyfill forString.prototype.repeat()
是可用的。
回答by Collin Green
Here is a fiddle showing what you're asking for:
这是一个小提琴,显示了您的要求:
<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);
Edit: Updated fiddle to correct off by one problem pointed out by alex
编辑:更新小提琴以纠正亚历克斯指出的一个问题