Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show only last 4 digits in bank account using javascript

Tags:

javascript

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,

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

I just replaced the creditCard with 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?

like image 905
ScrumMaster Guy Avatar asked Nov 28 '22 09:11

ScrumMaster Guy


1 Answers

To replace a string with x except for the last four characters in JavaScript, you could use (assuming str holds the string)...

var trailingCharsIntactCount = 4;

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

jsFiddle.

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.

jsFiddle.

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.

like image 88
alex Avatar answered Dec 15 '22 08:12

alex