我正在尝试创建一个将bbcode转换为html的类,但是replace不调用回调函数。

这就是我所拥有的

function bbcode(){
    this.bbcode_table = {};

    this.bbcode_table[/[asdf]/g] = function(match, contents, offset, input_string){
        return "hi";
    }
}

bbcode.prototype.toHTML = function(str){
    for (var key in this.bbcode_table){
        str = str.replace(key, this.bbcode_table[key]);
    }
    console.log(str); // asdf
}

var a = new bbcode;
a.toHTML("asdf");


上面的代码不起作用,但是,下面的代码运行良好。

text = "asdf";
text = text.replace(/[asdf]/g, function(match, contents, offset, input_string){
    return "hi";
});
console.log(text); // hihihihi


我究竟做错了什么?

最佳答案

因为key转换为string,所以功能replace不会捕获与"/[asdf]/g"的任何匹配项。

您可以对对象RegExp遵循此方法。



function bbcode() {
  this.bbcode_table = {};

  this.bbcode_table["[asdf]"] = {
    "cb": function(match, contents, offset, input_string) {
      return "hi";
    },
    "flag": "g"
  }
}

bbcode.prototype.toHTML = function(str) {
  for (var key in this.bbcode_table) {
    var regex = new RegExp(key, this.bbcode_table[key].flag);
    str = str.replace(regex, this.bbcode_table[key].cb);
  }
  console.log(str);
}

var a = new bbcode;
a.toHTML("asdf");

07-24 17:21
查看更多