show only last 4 digits in bank account using javascript - 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?

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.

Here is a fiddle showing what you're asking for:
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);
Edit: Updated fiddle to correct off by one problem pointed out by alex

Agreed with all above solutions.I just had one another approach.
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'));

Related

Manipulate text from form - JavaScript/Jquery

Hello I am working on a project and last night I had a thought that would make a lot of what I am wanting to do a heck of a lot easier, the only problem is I am not sure on the best way to tackle it. Let me explain....
I have a form on a website where a user enters a VIP ID that is in a pre-determined format and follows a logical naming convention.
Example: app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb
I want to pull out the following information from the entered text.
prod.platform.org.
Then I want to reverse it logically
.org.platform.prod
And then I want to replace the “.” For “/”
/org/platform/prod
And finally I want to add a postfix of “/open*”
/org/platform/prod/open*
So in short,
INPUT = app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb
OUTPUT = /org/platform/prod/open*
I am using javascript/jquery for everything else but I am pretty new to all of this so I tend not to know the best route to tackle a problem. If I need to provide some more detail I can do. Any help is much appreciated.
Or simple like this
var input = "app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb" ;
var output =
"/" +
input
.split(".")
.slice(1, 4)
.reverse()
.join("/") +
"/open";
var output =
"/" +
"app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb"
.split(".")
.slice(1, 4)
.reverse()
.join("/") +
"/open";
You can try below code :
var input = "app.prod.platform.org.dc1.prod.site.com-HTTP_80tcp-00000000-lb";
var tempArr = input.split(".");
var newArr = new Array();
for(var i=1;i<tempArr.length;i++){
if(tempArr[i]=="org" || tempArr[i]=="net"){
newArr.push(tempArr[i]);
break;
}
newArr.push(tempArr[i]);
}
newArr.reverse();
var output="/"+newArr.join("/")+"/open*";

Mask a portion of a String using RegExp

I'm trying to mask a portion of a string using JavaScript.
e.g. Mask second and third segment of credit-card number like this using regex:
4567 6365 7987 3783 → 4567 **** **** 3783
3457 732837 82372 → 3457 ****** 82372
I just want to keep the first 4 numbers and the last 5 characters.
This is my first attempt: /(?!^.*)[^a-zA-Z\s](?=.{5})/g
https://regex101.com/r/ZBi54c/2
You can try this:
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);
You could slice the first four digits and apply a replacement for the rest.
console.log(
['4567 6365 7987 3783', '3457 732837 82372'].map(
s => s.slice(0, 4) + s.slice(4).replace(/\d(?=.* )/g, '*')
)
);
The answer apparently satisfies the OP. Here is another solution using only Regexes:
function starry(match, gr1, gr2, gr3) {
var stars = gr2.replace(/\d/g, '*');
return gr1 + " " + stars + " " + gr3;
}
function ccStarry(str) {
var rex = /(\d{4})\s(\d{4}\s\d{4}|\d{6})\s(\d{4}|\d{5})/;
if (rex.test(str))
return str.replace(rex, starry);
else return "";
}
var s1 = "4567 6365 7987 3783";
var s2 = "3457 732837 82372";
var s3 = "dfdfdf";
console.log(ccStarry(s1));
console.log(ccStarry(s2));
console.log(ccStarry(s3));
This ensures that the pattern matches before trying any replacements. For example, in the third test case, it returns an empty string. The pattern can be updated to match other credit card patterns besides the ones given in the question.
I would like to elaborate more on the answer from #Nina Scholz, I use .slice() in the following sample code for masking the variable in 2 condition.
Just a simple variable var n = '12345567890'
Array object
// Single number
var n = '601115558888';
var singleNumber = n.slice(0, 4) + n.slice(4, n.length -4).replace(/\d/g,'*') + n.slice(n.length -4);
console.log(singleNumber);
// array of object
var obj = [{
contacts_name: 'Jason',
contacts_num : '651231239991'
},
{
contacts_name: 'King',
contacts_num : '60101233321'
}];
// Mask for the middle number, showing the first4 number and last4 number
// and replace the rest number with *
var num = obj.map((element, index) =>
element.contacts_num.slice(0,4)
+ element.contacts_num.slice(4, element.contacts_num.length-4).replace(/\d/g, '*')
+ element.contacts_num.slice(element.contacts_num.length -4)
);
console.log(num);
If it's JavaScript doing the regex masking, you've already failed because JS should never need to know the original card number, except when you've just received it from the user and are sending it to the server for the first time, in which case you shouldn't be masking it anyway so the user can check for typos.
I can't really help you there, you've already failed in the worst way.
Server-side, if the number is already broken into spaces*, then one option is: (in PHP but the same idea applies to all)
$parts = explode(" ",$fullnumber);
$first = array_shift($parts);
$last = array_pop($parts);
$middle = implode(" ",$parts);
$mask = preg_replace("/\d/","*",$middle);
$result = "$first $mask $last";
* it shouldn't be

Javascript array length through user input

I have a problem in Javascript I want to make a form which have one input text field and one button when I click on the button window.prompt is called.
It will prompt depend upon my array length but I want array length get through input text field when I write 10 it will prompt 10 times when I write 2 it will prompt 2 times.
How can i write this type of query?
I tried this code but its not working.
words = new Array (4);
function a() {
for ( k = 0 ; k < words.length ; k = k + 1 ) {
words[ k ] = window.prompt( "Enter word # " + k, "" ) ;
}
}
Maybe you forgot to call your function a().
Some remarks about your code:
You don't have to specify an initial array size, e.g. words = [] or words = new Array() is enough.
Also k=k+1 is usually written as k++.
A remark about asking questions:
Use punctuation to make sentences! Your whole question is one sentence.
Hopefully it's just the snippet of code but I hope you are using var somewhere to declare all those variables.
Otherwise this should do the trick, however not sure what you are trying to achieve but this sounds like a bad user experience.
Here is the jsffidle http://jsfiddle.net/R2bCz/1/
function Handler(event) {
var count = event.target.value;
var i = 0;
var words = [];
var word;
for (; i < count; i++) {
word = window.prompt("Enter word # " + i, "");
words.push(word);
}
}
$("#multi").on("change", Handler);

generate random string for div id

I want to display YouTube videos on my website, but I need to be able to add a unique id for each video that's going to be shared by users. So I put this together, and I have run into a little problem. I am trying to get the JavaScript to add a random string for the div id, but it's not working, showing the string:
<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
var div = randomString(8);
</script>
<div id='div()'>This text will be replaced</div>
<script type='text/javascript'>
jwplayer('div()').setup({
'flashplayer': 'player.swf',
'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
'controlbar': 'bottom',
'width': '470',
'height': '320'
});
</script>
I really like this function:
function guidGenerator() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
From Create GUID / UUID in JavaScript?
2018 edit: I think this answer has some interesting info, but for any practical applications you should use Joe's answer instead.
A simple way to create a unique ID in JavaScript is to use the Date object:
var uniqid = Date.now();
That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.
The problem with that value now is that you cannot use it as an element's ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.
var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
var uniqid = randLetter + Date.now();
This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.
Here is the reusable function to generate the random IDs :
function revisedRandId() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(2, 10);
}
// It will not start with the any number digit so it will be supported by CSS3
I think some folks here haven't really focused on your particular question. It looks like the problem you have is in putting the random number in the page and hooking the player up to it. There are a number of ways to do that. The simplest is with a small change to your existing code like this to document.write() the result into the page. I wouldn't normally recommend document.write(), but since your code is already inline and what you were trying do already was to put the div inline, this is the simplest way to do that. At the point where you have the random number, you just use this to put it and the div into the page:
var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');
and then, you refer to that in the jwplayer set up code like this:
jwplayer(randomId).setup({
And the whole block of code would look like this:
<script type='text/javascript' src='jwplayer.js'></script>
<script type='text/javascript'>
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
var randomId = "x" + randomString(8);
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({
'flashplayer': 'player.swf',
'file': 'http://www.youtube.com/watch?v=4AX0bi9GXXY',
'controlbar': 'bottom',
'width': '470',
'height': '320'
});
</script>
Another way to do it
I might add here at the end that generating a truly random number just to create a unique div ID is way overkill. You don't need a random number. You just need an ID that won't otherwise exist in the page. Frameworks like YUI have such a function and all they do is have a global variable that gets incremented each time the function is called and then combine that with a unique base string. It can look something like this:
var generateID = (function() {
var globalIdCounter = 0;
return function(baseStr) {
return(baseStr + globalIdCounter++);
}
})();
And, then in practical use, you would do something like this:
var randomId = generateID("myMovieContainer"); // "myMovieContainer1"
document.write('<div id="' + randomId + '">This text will be replaced</div>');
jwplayer(randomId).setup({
i like this simple one:
function randstr(prefix)
{
return Math.random().toString(36).replace('0.',prefix || '');
}
since id should (though not must) start with a letter, i'd use it like this:
let div_id = randstr('youtube_div_');
some example values:
youtube_div_4vvbgs01076
youtube_div_1rofi36hslx
youtube_div_i62wtpptnpo
youtube_div_rl4fc05xahs
youtube_div_jb9bu85go7
youtube_div_etmk8u7a3r9
youtube_div_7jrzty7x4ft
youtube_div_f41t3hxrxy
youtube_div_8822fmp5sc8
youtube_div_bv3a3flv425
I also needed a random id, I went with using base64 encoding:
btoa(Math.random()).substring(0,12)
Pick however many characters you want, the result is usually at least 24 characters.
Based on HTML 4, the id should start from letter:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
So, one of the solutions could be (alphanumeric):
var length = 9;
var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter
// Convert it to base 36 (numbers + letters), and grab the first 9 characters
// after the decimal.
var id = prefix + Math.random().toString(36).substr(2, length);
Another solution - generate string with letters only:
var length = 9;
var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);
Or you could use Cripto since it's already built in(except in IE11, I swear these guys havent updated in years!)
https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples
var id = new Uint32Array(10);
window.crypto.getRandomValues(id);
I also found this:
https://gist.github.com/6174/6062387#gistcomment-3255605
let length = 32;
let id = crypto.randomBytes(length).toString("base64");
There's a lot of ways to do this, but for most people, there's no reason to reinvent the wheel :)
A edited version of #jfriend000 version:
/**
* Generates a random string
*
* #param int length_
* #return string
*/
function randomString(length_) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
if (typeof length_ !== "number") {
length_ = Math.floor(Math.random() * chars.length_);
}
var str = '';
for (var i = 0; i < length_; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
For generating random ids, you can also use the standard crypto API with its randomUUID() function which is available in node.js (>=v16.7.0) and all relevant browsers except Safari:
const uuid = crypto.randomUUID()
console.log(uuid)
// prints e.g. "7f3f4512-fcf9-45fe-b726-512bba403426"
I would suggest that you start with some sort of placeholder, you may have this already, but its somewhere to append the div.
<div id="placeholder"></div>
Now, the idea is to dynamically create a new div, with your random id:
var rndId = randomString(8);
var div = document.createElement('div');
div.id = rndId
div.innerHTML = "Whatever you want the content of your div to be";
this can be apended to your placeholder as follows:
document.getElementById('placeholder').appendChild(div);
You can then use that in your jwplayer code:
jwplayer(rndId).setup(...);
Live example: http://jsfiddle.net/pNYZp/
Sidenote: Im pretty sure id's must start with an alpha character (ie, no numbers) - you might want to change your implementation of randomstring to enforce this rule. (ref)
May I an share an intuitive way to generate a randomID ?
const getRandomID = (length: number) => {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
Here is an easy one liner:
const generateUniqueID = (idLength) => [...Array(idLength).keys()].map((elem)=>Math.random().toString(36).substr(2, 1)).join("")
Where all you do is enter the idLength and it will return a unique id of that length.
generateUniqueID(23)
>>>'s3y9uebzuo73ih79g0s9p2q' // Id of length 23
First. Assign an id to your div. Like this:
<div id="uniqueid">This text will be replaced</div>
After that, add inside your <script> tag following code:
Document.getElementById("uniqueid").id = randomString(8);
window.btoa(String.fromCharCode(...window.crypto.getRandomValues(new Uint8Array(5))))
Using characters except ASCII letters, digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML5, an ID should start with a letter for compatibility.
function id(prefix = '', length = 7) {
let result = prefix;
for(let i = 0; i < length; i++) {
const random = Math.random();
result += String.fromCharCode(Math.floor(random * 26) + (random < .5 ? 65 : 97));
}
return result;
}
a random number between 0 and 25 is generated then added to either 65 or 97. When added to 65 it will give you an ascii code for a capital letter and when added to 97, an ascii code for a small letter.
Just use built-int crypto.randomUUID() which is supportted by all major browsers:
let uuid = crypto.randomUUID();
console.log(uuid);

What is the most optimized or simplest way to reduce a file name in javascript

I recently created a function in javascript that takes in a file name and a max character limit where the result needs to follow these rules:
Always include file extension
If shrinking occurs, leave the first part and last part of the file name intact.
Always replace the removed characters with '...'
If file length is under the max then do nothing
You can assume the max is a least 5 chars long
Now I've already solved this, but it got me thinking if there is a more elegant or simple way to do this in javascript using regular expressions or some other technique. It also gave me an opportunity to try out jsFiddle. So with that in mind here is my function:
function ReduceFileName(name, max){
if(name.length > max){
var end = name.substring(name.lastIndexOf('.'));
var begin = name.substring(0, name.lastIndexOf('.'));
max = max - end.length - 3;
begin = begin.substr(0,max/2) + '...' + begin.substr(begin.length-(max/2) , max/2 + 1);
return begin + end;
}
return name;
}
And here it is on js Fiddle with tests
I'm not sure that regular expressions will be necessarily more elegant, but so far I came up with the following which passes your tests:
function ReduceFileName(name, max){
if(name.length > max) {
var ell ="\u2026"; // defines replacement characters
var ext = (/\.[^\.]*$/.exec(name) || [""])[0]; // gets extension (with dot) or "" if no dot
var m = (max-ell.length-ext.length)/2; // splits the remaining # of characters
var a = Math.ceil(m);
var z = Math.floor(m);
var regex = new RegExp("^(.{"+a+"}).*(.{"+z+"})"+ext, "");
var ret = regex.exec(name);
return ret[1]+ell+ret[2]+ext;
}
return name;
}
Since I didn't get much activity on this, I'm assuming there isn't a much better way to do this, so I'll consider my method as the answer until someone else comes up with something else.
function ReduceFileName(name, max){
if(name.length > max){
var end = name.substring(name.lastIndexOf('.'));
var begin = name.substring(0, name.lastIndexOf('.'));
max = max - end.length - 3;
begin = begin.substr(0,max/2) + '...' + begin.substr(begin.length-(max/2) , max/2 + 1);
return begin + end;
}
return name;
}

Categories