Javascript String.replace回调不工作
我试图创建一个类来将bbcode转换为html,但replace不调用回调函数 这是我的Javascript String.replace回调不工作,javascript,node.js,regex,Javascript,Node.js,Regex,我试图创建一个类来将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){
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
我做错了什么?因为键被转换为字符串,所以函数替换没有捕获与/[asdf]/g的任何匹配
对于对象RegExp,可以采用这种方法
功能代码{
this.bbcode_table={};
此.bbcode_表[[asdf]]={
cb:函数匹配、内容、偏移量、输入字符串{
返回hi;
},
国旗:g
}
}
bbcode.prototype.toHTML=functionstr{
对于此.bbcode_表中的var键{
var regex=new RegExpkey,此.bbcode_表[key]。标志;
str=str.replaceregex,此.bbcode_表[key].cb;
}
console.logstr;
}
var a=新的bbcode;
a、 toHTMLasdf;String.replace需要一个正则表达式作为第一个参数,然后它将触发每次事件的回调。确保您的密钥是regexconsole.logkey outputs/[asdf]/g,非常确定它是regex@guijobtry printing console.logtypeof密钥