12
function maskify(cc) {
    var dd = cc.toString();
    var hash = dd.replace((/./g), '#');
    for (var i = (hash.length - 4); i < hash.length; i++) {
        hash[i] = dd[i];
    }
    return hash;
}

I am trying to replace all chars with # except for last 4. Why isn't it working?

Dan Lowe
  • 44,653
  • 17
  • 114
  • 109
Lukas David
  • 123
  • 1
  • 1
  • 4

3 Answers3

41

You could do it like this:

dd.replace(/.(?=.{4,}$)/g, '#');

var dd = 'Hello dude';
var replaced = dd.replace(/.(?=.{4,}$)/g, '#');
document.write(replaced);
MinusFour
  • 13,090
  • 3
  • 27
  • 36
  • 2
    @LukasDavid, it basically replaces all characters where there's more than 4 characters afterwards. So when it get to 4 characters before the end of the string, the regex will fail and won't replace those characters. – MinusFour Feb 07 '16 at 18:22
4

If you find the solution, try this trick

function maskify(cc) {
  return cc.slice(0, -4).replace(/./g, '#') + cc.slice(-4);
}
krolovolk
  • 426
  • 4
  • 16
0

To replace a character in a string at a given index, hash[i] = dd[i] doesn't work. Strings are immutable in Javascript. See How do I replace a character at a particular index in JavaScript? for some advice on that.

Community
  • 1
  • 1
Adi Levin
  • 5,025
  • 1
  • 16
  • 25