Skip to content

Instantly share code, notes, and snippets.

@ahmadalibaloch
Created October 11, 2019 11:58
Show Gist options
  • Save ahmadalibaloch/ec97aaebf12853b018239aa05f40dea9 to your computer and use it in GitHub Desktop.
Save ahmadalibaloch/ec97aaebf12853b018239aa05f40dea9 to your computer and use it in GitHub Desktop.
Credit Card maskify in Javascript
function maskify(creditCard) {
if (creditCard.length < 6) return creditCard;
const last4Characters = creditCard.substr(-4);
const firstCharacter = creditCard.substr(0, 1);
const maskingCharacters = creditCard.substr(1, creditCard.length - 5).replace(/\d/g, '#');
return `${firstCharacter}${maskingCharacters}${last4Characters}`;
}
// let assert = require('chai').assert
// require('mocha').describe;
// require('mocha').it;
// describe('Challenge - Maskify', () => {
// it('should return a string ouput', () => {
// assert.typeOf(maskify(""), 'string');
// });
// it('should mask the digits of standard credit cards', () => {
// assert.equal(maskify("5512103073210694"), "5###########0694");
// });
// it('should not mask the digits of short credit cards', () => {
// assert.equal(maskify("54321"), "54321");
// });
// it('should not mask the - or special characters between digits', () => {
// assert.equal(maskify("5432-1312-1231/4567"), "5###-####-####/4567");
// });
// it('should return non digit characters without masking', () => {
// assert.equal(maskify("Skippy"), "Skippy");
// });
// it('should handle the empty string input correctly', () => {
// assert.equal(maskify(""), "");
// });
// });
@AlaeddineMessadi
Copy link

You can easily use Regular expression

function maskify(input) {
  return input.replace(/.(?=.{4})/g, "#");
}

@ahmadalibaloch
Copy link
Author

ahmadalibaloch commented Feb 6, 2021

thanks for the suggestion @AlaeddineMessadi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment