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
4 Réponses
+ 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);
}
+ 1
var str = "aeroplane";
var newStr = str.replace(/(.{2}).*(.{2})/, '$1***$2');
console.log(newStr);
0
In java:
String s = “aeroplane”;
System.out.println(s.replaceAll(s.substring(2, s.length() - 2), “java”));
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