根据正则表达式的匹配结果将匹配项替换为*
function regReplace(reg, str){ var result, //最终输出结果
out, //每次运行正则exec返回的匹配结果。
index, //匹配项在字符串中位置
length; //匹配项长度
result = str.split(""); //将待匹配的字符串分开成数组,等待处理
while(out = reg.exec(str)){ //当匹配成功返回out数组,如果没有匹配项或达到字符串末尾返回null
length = out[0].length; //匹配项长度
for(var i = 0; i < length; i++){ //从开始匹配的位置,根据匹配项长度循环替换为*
index = reg.lastIndex;
result.splice(index -length + i, 1, "*");
}
}
return reg + "\n"+ str + "\n" + result.join(""); //返回结果
}
测试一:
var strs = 'yangxunwu@164.com';var regs = /[\w\-]+@[a-zA-Z\d]((\-)?[a-zA-Z\d])*(\.[a-zA-Z\d]((\-)?[a-zA-Z\d])*)*(\.[a-zA-Z]{2,4})/g;
var outCome = regReplace(regs, strs);
console.log(outCome);
输出:/[\w\-]+@[a-zA-Z\d]((\-)?[a-zA-Z\d])*(\.[a-zA-Z\d]((\-)?[a-zA-Z\d])*)*(\.[a-zA-Z]{2,4})/g
yangxunwu@164.com
*****************
测试二:
var str = 'a aa aaa aaaa ab abb abbba abcba';var reg = /ab+/g;
输出:/ab+/g
a aa aaa aaaa ab abb abbba abcba
a aa aaa aaaa ** *** ****a **cba