Replacing a character after a specific character length

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

, - , . , .

.

+4
3

, .

text.substring(3).replace(/\S/g,'*'); O(n) .

Array.prototype.join() :

var newText = text.substring(0,3) + Array(text.length-2).join("*");

, .join(), , . ; , , .

, , 0(log n).

, .

var longerThanNeeded = "***************************";
var newText = text.substring(0,3) + longerThanNeeded.substring(0,text.length-3);

.

+3

(^.{3}).|. w/\1*

( 3 )

(               # Capturing Group (1)
  ^             # Start of string/line
  .             # Any character except line break
  {3}           # (repeated {3} times)
)               # End of Capturing Group (1)
.               # Any character except line break
|               # OR
.               # Any character except line break
+2

s.replace(new RegExp(".(?=.{0," + (s.length-4) + "}$)", "g"), '*')

. JS:

var text = 'ABCDEFG';
var threshold = 3; // Start replacing with * after this value
if (text.length > threshold) {
  text = text.replace(new RegExp(".(?=.{0," + (text.length-threshold-1) + "}$)", "g"), '*');
}
console.log(text);
Hide result

, threshold - 3, .(?=.{0,3}$): char, char ., 0 3 , (.{0,3}) ($). (?=...) , , ( ).

, . [^] [\s\S].

+1

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


All Articles