I am trying to execute a function to replace the entire character after a certain character length with an asterisk, and so far I have done it like this.
var text = 'ABCDEFG';
var newText = text.substring(0,3) + text.substring(3).replace(/\S/g,'*');
If I gave me what I need, but it is rather inefficient, as I understand it, and I am trying to change it to make it more efficient.
text.replace(/.{4}$/,'*');
Unfortunately, the result was not expected, and it should be rigid, the length of 4 counts at the back, and this will not work if the word length is different.
Is there any regex method that can replace all other characters with an asterisk after a certain character length (in this case, 3).
Any help on this would be appreciated. Thank.
Edited:
As a conclusion of the proposal and discussion
, .
text.replace(/(\w{3}).*/g, "$1"+(new Array(text.length -3 + 1).join( '*' )));
by @Keerthana Prabhakaran
text.replace(new RegExp(".(?=.{0," + (text.length-4) + "}$)", "g"), '*')
by @Wiktor Stribiżew
var longerThanNeeded = "***************************";
var newText = text.substring(0,3) + longerThanNeeded.substring(0,text.length-3);
by @matthewninja
(^.{3}).|. and replace w/ \1*
by @alpha bravo
, - , . , .
.