To replace emails, phone numbers, and addresses in a string while preserving the original format, you can use regular expressions to identify and replace these sensitive patterns with placeholder text. Regular expressions (regex) are a powerful tool for pattern matching, which allows you to search for specific patterns in a string and replace them with desired content.

Here's a JavaScript example of how you can achieve this:

function maskSensitiveData(inputString) { // Regular expressions to match emails, phone numbers, and addresses const emailRegex = /[\w.-]+@[\w-]+\.[\w.-]+/g; const phoneRegex = /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g; const addressRegex = /\d+\s+[\w\s]+,\s+[\w\s]+,\s+[\w\s]+,\s+\d+/g; // Replace emails, phone numbers, and addresses with placeholder text const maskedString = inputString .replace(emailRegex, "[Email]") .replace(phoneRegex, "[Phone]") .replace(addressRegex, "[Address]"); return maskedString; } // Example usage const originalText = "Contact us at or call 123-456-7890. Our address is 123 Main St, Anytown, USA, 12345."; const maskedText = maskSensitiveData(originalText); console.log(maskedText);

In the above example, we define three regular expressions for matching emails, phone numbers, and addresses. The g flag in each regex allows global matching, which means it will find all occurrences in the input string. The replace() method is then used to replace the matched patterns with the desired placeholder text ([Email], [Phone], and [Address]).

Please note that this example provides a simple illustration of how you can mask sensitive data using regular expressions. In practice, you may need to adjust the regular expressions to handle various formats and edge cases specific to your use case. Additionally, consider handling other types of sensitive information, such as names or social security numbers, if needed.

It's also important to note that masking sensitive data is not a foolproof security measure, and it may not be sufficient in all cases. If you need stronger data protection, especially in the context of user data and security, consider using appropriate encryption and data handling techniques, complying with privacy regulations, and storing sensitive data securely.

Have questions or queries?
Get in Touch