views:

285

answers:

1

I'm trying to create a bbcode filtering solution that works with both PHP and Javascript. Right now I'm working on the javascript. I'm having trouble getting the new RegExp constructor to recognize the patterns in my json. Here's a small bit of sample code that reproduces the issue. Any insight would be greatly appreciated!

bbcode.json

{"bbcode_regex": [
      {"regex": "<p>", "bbcode": ""},
      {"regex": "<\/p>", "bbcode": ""},
}

global.js

function html2bbcode(html) {
    var bbcode = html;

    jQuery.get("bbcode.json", {}, function(json) {
     for(var i in json.bbcode_regex) { 
      bbcode = bbcode.replace(new RegExp(json.bbcode_regex[i].regex, "g"), json.bbcode_regex[i].bbcode)
      console.log(new RegExp("/<p>/"));
     }
    }, 'json');

    return bbcode;
}

Note that I'm using FireBug and the console.log RegExp is there just for experimenting / debug purposes. It seems like no matter what I put in as the first argument for the new RegExp it only logs an empty object like {}. I'm no so much worried about the PHP right now, just the javascript. Thanks!

+3  A: 

The line

return bbcode;

will return undefined, it will initialized later, when ajax request was done. Use callback:

function html2bbcode(html, callback) {
    var bbcode = html;

    jQuery.get("bbcode.json", {}, function (json) {
        for (var i in json.bbcode_regex) { 
            bbcode = bbcode.replace(new RegExp(json.bbcode_regex[i].regex, "g"), json.bbcode_regex[i].bbcode);
        }
        callback(bbcode);
    }, 'json');

    return false;
}
Anatoliy
Untrue. That line returned an unfiltered version of bbcode because the Regex object isn't instantiating properly. If I return false then I get "false" for the text that shows up on the page.
aphelionz
No aphelionz, Anatoliy is correct. You get unfiltered content back because `html2bbcode()` returns before the AJAX callback executes. You *may also* have a RegExp problem, but that doesn't mean Anatoliy is wrong.
Peter Bailey
Yes, you are right, it's return html, but it's the same as passed to function, it means, than function doing nothing with passed html. Expected behavior - replace with regex, fetched via AJAX.
Anatoliy
Ah, my mistake! I still think I have a RegExp problem though.
aphelionz
I've tested and was not found any problems with regex: 'aa<p>'.replace(new RegExp('<p>', "g"), ''); returns 'aa' as expected.
Anatoliy
Awesome. Thank you for all your help!
aphelionz