0

[SOLVED] regex to replace all characters of a string except first and last two characters.

I need a regex to replace all characters of a word except 2 first and last characters. eg: aeroplane => ae*****ne SoloLearn => So*****rn

20th Nov 2021, 3:52 PM
Bibek Oli
Bibek Oli - avatar
4 Antworten
+ 2
var str = "ehshsnsnh"; if(str.length <= 4){ console.log(str) }else{ var asterisk = "*".repeat(str.length - 4); var newStr = str.replace(/(.{2}).*(.{2})/, '$1'+asterisk+'$2'); console.log(newStr); }
20th Nov 2021, 6:58 PM
Jairo Soto
Jairo Soto - avatar
+ 1
var str = "aeroplane"; var newStr = str.replace(/(.{2}).*(.{2})/, '$1***$2'); console.log(newStr);
20th Nov 2021, 6:10 PM
Jairo Soto
Jairo Soto - avatar
0
In java: String s = “aeroplane”; System.out.println(s.replaceAll(s.substring(2, s.length() - 2), “java”));
20th Nov 2021, 6:00 PM
Juan Debenedetti
Juan Debenedetti - avatar
0
Jairo Soto it is nearly what I wanted except it is not showing exactly same number of stars as hidden characters. Example: In "aeroplane", there are 5 characters to be hidden excluding first and last two characters, so it should show 5 stars in the middle like ae*****ne. Same rule for every other words. And normally if the word is 4 or less characters, it should show original string
20th Nov 2021, 6:18 PM
Bibek Oli
Bibek Oli - avatar