Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to mask a number with stars except the last 4 digits in JavaScript

4 Answers

0 votes
const cardNumber = '9003125334656789';

const last4Digits = cardNumber.slice(-4);

const maskedNumber = last4Digits.padStart(cardNumber.length, '*');

console.log(maskedNumber);



/*
run:

************6789

*/

 



answered May 28, 2024 by avibootz
0 votes
function maskNumber(value, maskChar = '*') {
  const str = String(value);
  
  // Return as-is if 4 or fewer characters
  if (str.length <= 4) return str;
  
  return str.slice(-4).padStart(str.length, maskChar);
}

// Examples:
console.log(maskNumber('1234567890123456')); // ************3456
console.log(maskNumber(9876543210));         // ******3210
console.log(maskNumber('123'));              // 123


/*
run:

************3456
******3210
123

*/

 



answered 8 hours ago by avibootz
0 votes
function maskWithRegex(value, maskChar = '*') {
  const str = String(value);
  return str.replace(/.(?=.{4})/g, maskChar);
}

// Example:
console.log(maskWithRegex('1234567890123456')); // ************3456


/*
run:

************3456

*/

 



answered 8 hours ago by avibootz
0 votes
function maskDigitsKeepFormat(value, visibleDigits = 4, maskChar = '*') {
  const str = String(value);
  const totalDigits = (str.match(/\d/g) || []).length;
  let digitsToMask = Math.max(0, totalDigits - visibleDigits);

  return str.replace(/\d/g, (match) => {
    if (digitsToMask > 0) {
      digitsToMask--;
      return maskChar;
    }
    return match;
  });
}

// Examples:
console.log(maskDigitsKeepFormat('1234-5678-9012-3456')); // ****-****-****-3456
console.log(maskDigitsKeepFormat('+1 (800) 555-0199'));    // +* (***) ***-0199


/*
run:

****-****-****-3456
+* (***) ***-0199

*/

 



answered 8 hours ago by avibootz

Related questions

...