Replace all characters with # except the 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'm trying to replace all # characters except for the last 4. Why doesn't it work?

+5
source share
2 answers

To replace a character in a string with a given index, hash[i] = dd[i] does not work. Strings are immutable in Javascript. See How to replace a character in a specific index in JavaScript? for some tips on this.

0
source

You can do it as follows:

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

 var dd = 'Hello dude'; var replaced = dd.replace(/.(?=.{4,}$)/g, '#'); document.write(replaced); 
+13
source

Source: https://habr.com/ru/post/1242493/


All Articles