最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replacing character after certain character length - Stack Overflow

programmeradmin1浏览0评论

I trying to do a function to replace all the character after a certain length of character to asterisk, and so far what i did is like this.

var text = 'ABCDEFG';
var newText = text.substring(0,3) + text.substring(3).replace(/\S/g,'*');

If would give me what I need, but it is fairly inefficient as I understand it, and i trying to change it to make it more efficient.

text.replace(/.{4}$/,'*');

Unfortunately the result is not i expected and also it need to be hardcode the length of 4 counting from behind, which it wont work if the word's length is different.

Is there any regex method that able to replace all other character to asterisk after certain length of character (in this case is 3).

Any help to this will be appreciated. Thanks.

Edited: As conclusion of the suggestion and discussion

Alternative way to solve the problem, which giving the almost identical result as my solution.

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

As discuss with some of the people, due to the efficiency of the code are almost the same even for the original code that I make of. Therefore it stated as side discussing.

Appreciated the helps once again.

I trying to do a function to replace all the character after a certain length of character to asterisk, and so far what i did is like this.

var text = 'ABCDEFG';
var newText = text.substring(0,3) + text.substring(3).replace(/\S/g,'*');

If would give me what I need, but it is fairly inefficient as I understand it, and i trying to change it to make it more efficient.

text.replace(/.{4}$/,'*');

Unfortunately the result is not i expected and also it need to be hardcode the length of 4 counting from behind, which it wont work if the word's length is different.

Is there any regex method that able to replace all other character to asterisk after certain length of character (in this case is 3).

Any help to this will be appreciated. Thanks.

Edited: As conclusion of the suggestion and discussion

Alternative way to solve the problem, which giving the almost identical result as my solution.

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

As discuss with some of the people, due to the efficiency of the code are almost the same even for the original code that I make of. Therefore it stated as side discussing.

Appreciated the helps once again.

Share Improve this question edited Aug 3, 2017 at 10:42 Dean asked Aug 3, 2017 at 3:52 DeanDean 67813 silver badges34 bronze badges 11
  • 1 Why is your code inefficient? – Nisarg Shah Commented Aug 3, 2017 at 3:58
  • 1 It took 2 action to did what i need, which i hope it done in 1. although is not really a must, just hope it can be done in more pact way – Dean Commented Aug 3, 2017 at 4:03
  • 1 That's incorrect. Even if a regex did what you want, it would internally be doing similar sets of operations (or more). Just because your code is larger, doesn't mean it's bad. – Nisarg Shah Commented Aug 3, 2017 at 4:05
  • 1 text.replace(/(\w{3}).*/g, "$1"+(new Array(text.length -3 + 1).join( '*' ))); would help! Javascript strings are immutable and hence, the ways you've tried is also actually efficient. To make the code generic, assign 3 to a variable and use that everywhere in the code so that you need to change only in one place if the length varies! – Keerthana Prabhakaran Commented Aug 3, 2017 at 4:24
  • 1 I think s.replace(new RegExp(".(?=.{0," + (s.length-4) + "}$)", "g"), '*') will work when you need to replace each but the first char. Replace . with [\s\S] to support newline matching. – Wiktor Stribiżew Commented Aug 3, 2017 at 7:54
 |  Show 6 more ments

3 Answers 3

Reset to default 3

I hope I'm not overthinking this.

text.substring(3).replace(/\S/g,'*'); has linear time plexity O(n) and isn't terribly inefficient.

I initially thought of using Array.prototype.join() like so:

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

Before realizing that .join() needs to run for every element of the array, which results in linear time plexity, just like your original solution. This wouldn't improve the solution at all; All I've done is inflate the space plexity.

I then went on to think of creating the element to be joined by copying and increasing the size of the prior element, which would get us down to 0(log n) plexity.

Finally, I saw the most obvious solution.

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

which will run in constant time.

You could use this pattern (^.{3}).|. and replace w/ \1* Demo

(Please note limitation for strings less than 3 characters in length)

(               # 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

You may use

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

See a JS demo:

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);

Here, if threshold is 3, the pattern will look like .(?=.{0,3}$): it matches any char but a line break char with . that is followed with 0 to 3 chars other than line break chars (.{0,3}) and the end of string position ($). The (?=...) is a positive lookahead that only checks for the pattern match, but does not move the regex index and does not add the matched text to the match value (allowing subsequent consecutive symbol check).

To enable matching line breaks, replace . with [^] or [\s\S].

发布评论

评论列表(0)

  1. 暂无评论