14
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
  • 51,713
  • 20
  • 123
  • 112
Lukas David
  • 143
  • 1
  • 1
  • 4

4 Answers4

44

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,913
  • 3
  • 30
  • 39
  • 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
  • 464
  • 6
  • 18
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,165
  • 1
  • 17
  • 26
0
function maskify(cc) {
  let arr = cc.split('');
  for (let i = 0; i < arr.length - 4; i++){
    arr[i] = '#';
  }
  return arr.join('');
}
Lovely
  • 1