party34
party34

Reputation: 99

String.replace callback not working

I'm trying to make a class to convert bbcode to html but replace doesn't call callback function.

Here's what i have

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");

The code above is not working, however, the code below works well.

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

What am I doing wrong?

Upvotes: 0

Views: 718

Answers (1)

Ele
Ele

Reputation: 33726

Because the key is converted to string, so the funtion replace is not capturing any match with "/[asdf]/g".

You can follow this approach with the object 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");

Upvotes: 1

Related Questions