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标签

posted on 2016-01-26 17:00  迷茫小飞侠  阅读(253)  评论(0编辑  收藏  举报

导航