简体   繁体   中英

Regular expression to replace middle chars of a string

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM