How to replace some preceding characters with a constant 4 asterisks and display the last 3 as well - JavaScript?

In JavaScript, you can mask sensitive data by replacing preceding characters with asterisks while keeping the last few characters visible. This is commonly used for phone numbers, credit cards, or account numbers.

Problem Statement

Given these input values:

'6778922'
'76633 56 1443'
'8888 4532 3232 9999'

We want to replace all preceding characters with 4 asterisks and display only the last 3 characters:

**** 922
**** 443
**** 999

Using replace() with Regular Expression

The replace() method with a regex pattern can capture the last 3 characters and replace everything else with asterisks:

const hideDataWithDot = value => value.replace(/.+(.{3})$/, "**** $1");

console.log(hideDataWithDot('6778922'));
console.log(hideDataWithDot('76633 56 1443'));
console.log(hideDataWithDot('8888 4532 3232 9999'));
**** 922
**** 443
**** 999

How the Regex Works

The regex pattern /.+(.{3})$/ breaks down as:

  • .+ - Matches one or more characters (the preceding part)
  • (.{3}) - Captures exactly 3 characters (the last 3)
  • $ - Ensures matching at the end of string
  • "**** $1" - Replaces with 4 asterisks + space + captured group

Alternative Approach Using slice()

You can also achieve this using string slicing:

const maskData = value => "**** " + value.slice(-3);

console.log(maskData('6778922'));
console.log(maskData('76633 56 1443'));
console.log(maskData('8888 4532 3232 9999'));
**** 922
**** 443
**** 999

Comparison

Method Code Complexity Performance Flexibility
replace() with regex Medium Slightly slower High - easy to modify pattern
slice() method Simple Faster Lower - hardcoded format

Conclusion

Both methods effectively mask sensitive data. Use replace() with regex for flexible patterns, or slice() for simple, consistent formatting requirements.

Updated on: 2026-03-15T23:19:00+05:30

954 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements