DEV Community

loading...

Discussion on: String Pad in JavaScript

Collapse
functional_js profile image
Functional Javascript

Excellent work Samantha.

A couple of these might come in handy so I utility-ized them...

Utility 1

/**
@func
pretty format two columns as a text-based table

@param {string[][]} a
@return {string} multiline formatted str
*/
const formatTwoCol = a => a.map(([col1, col2]) => col1 + col2.padStart(20 - col1.length)).join("\n");

//@tests
const purchaseItems = [
  ["Masks", "9.99"],
  ["Shirt", "20.00"],
  ["Jacket", "200.00"],
  ["Gloves", "10.00"],
];

console.log(formatTwoCol(purchaseItems));
/*
output:
Masks           9.99
Shirt          20.00
Jacket        200.00
Gloves         10.00

*/

Utility 2

/**
@func
mask a credit card number with asterisks

@tags
security

@algor
get last 4 numbers
- then left-pad these 4 numbers with asterisks
- by the count of the remaining numbers

@param {string} cc - Credit Card number as a string, space separated per 4 digits
@return {string} - masked str
*/
const maskCreditCardNumber = cc => cc.slice(-4).padStart(cc.length, "*");

//@tests
console.log(maskCreditCardNumber("2222 2222 2222 2222"));
/*
output:
***************2222

*/
Collapse
samanthaming profile image
Samantha Ming Author

WHoa! these are fantastic 👏 Thanks for sharing 🙌