replace 使用函数作为第二参数

var sToChange = “The sky is red.”;
var reRed = /red/;
var sResultText = sToChange.replace(reRed, function(sMatch) {
          return “blue”;
});

 

sMatch  指的是被匹配到到的对象, return 返回替换的对象

 

var reBadWords = /badword|anotherbadword/gi;
var sUserInput = “This is a string using badword1 and badword2.”;
var sFinalText = sUserInput.replace(reBadWords, function(sMatch) {
return sMatch.replace(/./g, “*”);
});
alert(sFinalText);  //output “This is a string using ******* and **************”
屏蔽关键字

 

String.prototype.stripHTML = function () {
var reTag = /<(?:.|s)*?>/g;
return this.replace(reTag, “”);
};
去除html标签

原文地址:https://www.cnblogs.com/chuangweili/p/5160961.html