I would like to replace middle 4 characters of a string with ****
For example: ABCDEFG should become AB****G
Please suggest a Regex to achieve this.
Note: The length of the string is always same.
CodePudding user response:
its just 1 line no need to use regex if you replace the same index every time:
mystr='ABCDEFG'
newstr=mystr[0:2] '****' mystr[-1]
CodePudding user response:
Found the solution that I was looking for:
var s="ABCDEFG"
var reg=/\b(\w{2})\w (\w)\b/g
s.replace(reg, '$1**$2');
output: AB****G
This will replace all the middle chars except first 2 and last 1 char in a string.