How to replace characters except last with a mask character in JavaScript?

JavaScript provides the replace() method to modify strings by replacing specific characters or patterns. A common requirement is to mask all characters in a string except the last one, which is useful for hiding sensitive data like credit card numbers or passwords.

Syntax

To replace all characters except the last one with a mask character, use this regex pattern:

str.replace(/.(?=.)/g, maskCharacter);

The regex /.(?=.)/g matches any character (.) that has at least one character after it ((?=.)), effectively selecting all characters except the last one.

How It Works

  • . - Matches any single character

  • (?=.) - Positive lookahead that ensures there's another character following

  • g - Global flag to replace all matches, not just the first

Example 1: Basic Implementation

Here's a simple example that replaces all characters except the last with "x":

<html>
<body>
    <div id="result1"></div>
    <div id="result2"></div>
    <script>
        var str = "Hello world";
        document.getElementById("result1").innerHTML = "Original String: " + str;
        
        var newStr = str.replace(/.(?=.)/g, "x");
        document.getElementById("result2").innerHTML = "String after replacement: " + newStr;
    </script>
</body>
</html>
Original String: Hello world
String after replacement: xxxxxxxxxd

Example 2: Credit Card Number Masking

A practical example for masking credit card numbers, showing only the last digit:

<html>
<body>
    <div id="cardResult"></div>
    <script>
        var cardNumber = "1234567890123456";
        var maskedCard = cardNumber.replace(/.(?=.)/g, "*");
        
        document.getElementById("cardResult").innerHTML = 
            "Card Number: " + cardNumber + "<br>" +
            "Masked Card: " + maskedCard;
    </script>
</body>
</html>
Card Number: 1234567890123456
Masked Card: ***************6

Example 3: Interactive String Masking

An interactive example where users can input their own string and mask character:

<html>
<body>
    <p>Enter String: </p>
    <input type="text" id="myStr" value="TutorialsPoint">
    
    <p>Enter mask character: </p>
    <input type="text" id="myMask" value="#" maxlength="1">
    
    <p>String after replacement:</p>
    <div id="result"></div>
    
    <button onclick="replaceStr()">Replace</button>
    
    <script>
        function replaceStr() {
            var str = document.getElementById("myStr").value;
            var mask = document.getElementById("myMask").value || "*";
            
            if (str.length === 0) {
                document.getElementById("result").innerHTML = "Please enter a string";
                return;
            }
            
            var newStr = str.replace(/.(?=.)/g, mask);
            document.getElementById("result").innerHTML = newStr;
        }
        
        // Show initial result
        replaceStr();
    </script>
</body>
</html>

Common Use Cases

  • Masking credit card numbers for security

  • Hiding sensitive data in logs or displays

  • Creating privacy-friendly user interfaces

  • Generating placeholder text for forms

Key Points

  • The pattern /.(?=.)/g ensures the last character remains visible

  • Works with strings of any length (minimum 1 character)

  • Can use any character as a mask replacement

  • Maintains the original string length

Conclusion

The replace() method with regex pattern /.(?=.)/g provides an elegant solution for masking all characters except the last one. This technique is particularly useful for protecting sensitive information while maintaining data context.

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

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements