Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Masking a string JavaScript
Masking a string means replacing certain characters with asterisks (*) or other symbols to hide sensitive information like passwords, credit card numbers, or personal data. In JavaScript, we can create a function to mask specific portions of a string while keeping the rest visible.
Understanding String Masking
String masking is commonly used in applications to protect sensitive data while still showing partial information for verification purposes. For example, displaying a credit card number as "1234-****-****-5678" or an email as "j***@example.com".
Basic Masking Function
Here's a function that masks characters between specified start and end positions:
function maskString(str, start, end) {
// Validate inputs
if (!str || start < 0 || start >= str.length || end < 0 || end > str.length || start >= end) {
return str;
}
// Calculate mask length
const maskLength = end - start;
// Create masked string
const maskedStr = str.substring(0, start) + "*".repeat(maskLength) + str.substring(end);
return maskedStr;
}
// Example usage
const phoneNumber = "9876543210";
const maskedPhone = maskString(phoneNumber, 2, 8);
console.log("Original:", phoneNumber);
console.log("Masked:", maskedPhone);
Original: 9876543210 Masked: 98******10
Advanced Masking Examples
Here are different masking approaches for common use cases:
// Mask email address
function maskEmail(email) {
const atIndex = email.indexOf('@');
if (atIndex <= 1) return email;
return email[0] + '*'.repeat(atIndex - 1) + email.substring(atIndex);
}
// Mask credit card (show first 4 and last 4 digits)
function maskCreditCard(cardNumber) {
if (cardNumber.length < 8) return cardNumber;
const visibleStart = cardNumber.substring(0, 4);
const visibleEnd = cardNumber.substring(cardNumber.length - 4);
const maskLength = cardNumber.length - 8;
return visibleStart + '*'.repeat(maskLength) + visibleEnd;
}
// Examples
console.log("Email masking:");
console.log(maskEmail("john.doe@example.com"));
console.log(maskEmail("a@test.com"));
console.log("\nCredit card masking:");
console.log(maskCreditCard("1234567890123456"));
console.log(maskCreditCard("1234"));
Email masking: j*******@example.com a@test.com Credit card masking: 1234********3456 1234
Flexible Masking Function
This enhanced version allows custom masking characters and patterns:
function flexibleMask(str, options = {}) {
const {
start = 0,
end = str.length,
maskChar = '*',
keepStart = 0,
keepEnd = 0
} = options;
// Validate inputs
if (!str || str.length < keepStart + keepEnd) return str;
const startPart = str.substring(0, Math.max(start, keepStart));
const endPart = str.substring(Math.min(end, str.length - keepEnd));
const maskLength = Math.max(0, str.length - startPart.length - endPart.length);
return startPart + maskChar.repeat(maskLength) + endPart;
}
// Examples with different options
const sensitiveData = "SecretPassword123";
console.log("Default masking:", flexibleMask(sensitiveData, { start: 2, end: 12 }));
console.log("Keep first 3, last 2:", flexibleMask(sensitiveData, { keepStart: 3, keepEnd: 2 }));
console.log("Custom character:", flexibleMask(sensitiveData, { start: 1, end: 10, maskChar: '#' }));
Default masking: Se**********123 Keep first 3, last 2: Sec************23 Custom character: S#########ord123
Algorithm Analysis
Time Complexity: O(n) where n is the length of the input string, due to substring operations and string concatenation.
Space Complexity: O(n) for creating the new masked string.
Key Points
- Always validate input parameters to avoid errors
- Use
substring()method to extract parts of the string -
repeat()method efficiently creates repeated characters - Consider different masking patterns based on data type
- Ensure the original string length is preserved when needed
Conclusion
String masking is essential for protecting sensitive data in applications. The basic approach uses substring operations and character repetition, while advanced implementations can handle various masking patterns and requirements efficiently.
