Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all chars with #, except for last 4

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?

like image 374
Lukas David Avatar asked Feb 07 '16 17:02

Lukas David


People also ask

How do you replace all characters?

Summary. To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

What do the Replace All () do?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.

How do I replace multiple characters in a string?

Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.


2 Answers

You could do it like this:

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

var dd = 'Hello dude';
var replaced = dd.replace(/.(?=.{4,}$)/g, '#');
document.write(replaced);
like image 161
MinusFour Avatar answered Oct 02 '22 03:10

MinusFour


If you find the solution, try this trick

function maskify(cc) {
  return cc.slice(0, -4).replace(/./g, '#') + cc.slice(-4);
}
like image 37
krolovolk Avatar answered Oct 02 '22 05:10

krolovolk