隐藏前面两位
function formatIP(ip){ return "*.*."+ip.replace(/^(?:\d+\.){2}/, '') }
隐藏后面两位
console.log(s.replace(/(?:\.\d+){2}$/, '') + ".*.*");
let ip1 = '192.168.12.99'; let pattern = /^(\d+\.){2}\d+$/; console.log(ip1.replace(pattern, '*.*.$2')); // Output: *.*.12.99
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=<device-width>, initial-scale=1.0"> <title>Document</title> </head> <body> <script> function formatIp(ip) { let str = ip.split('.') str[0] = str[1] = '*' return str.join('.') } function isIp(ip) { var reg = /^((?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d))$/ return reg.test(ip) } console.log(formatIp('172.168.2.1')) var ip = '12.168.11.13'; var result = ip.replace(/^(\d{1,3}){2}/, '*'); console.log(result) var s = '24.210.199.111'; console.log(s.replace(/(?:\.\d+){2}$/, '') + ".*.*"); console.log("*.*." + s.replace(/^(?:\d+\.){2}/, '')) function formatIP(ip) { return "*.*." + ip.replace(/^(?:\d+\.){2}/, '') } console.log(formatIP('192.168.1.0')) console.log('192.168.1.0'.replace(/^(\*\.)(.*)$/, '$1$2')) console.log(isIp('192.168.1.1')) console.log(isIp('192.168.11.12')) console.log(isIp('11.12')) let ip1 = '192.168.12.99'; let pattern = /^(\d+\.){2}\d+$/; console.log(ip1.replace(pattern, '*.*.$2')); // Output: *.*.12.99 </script> </body> </html>