4

Possible Duplicate:
Converting user input string to regular expression
javascript new regexp from string

I am having a little bit of a problem with regex in javascript (I'm not too used to regex in javascript just yet). I wanna replace some stuff in a string and I noticed the syntax for writing regex seems to be without ' or " like this: var replacedtitle = title.replace(/\[.*?\]/g, "");

Now this all work as intended, but I want the user to be able to add his own regexes from the interface without changing the code (I'm doing a private project for a friend who doesn't code, and I want to be able to just send him the regexes to input when something new needs to be replaced instead of me repackaging everything every time). I did this by having a xul textbox (this is a firefox addon, but should be the same as if it was a html textbox) where he inputs the regexes, it gets added to a json object and saved. I tried doing something like this:

var replacedtitle = "";
for(a = 0; a < regex.data.length;a++){
    replacedtitle = title.replace(regex.data[a].regex, "");
}

but it wont work. I suspect it's because regex.data[a].regex would be taken as a string, yet replace() doesn't seem to take string as the first parameter, right?

I am a bit uncertain about this, any help would be much appreciated.

Community
  • 1
  • 1
galaxyAbstractor
  • 537
  • 1
  • 4
  • 13

3 Answers3

13

You can create a RegEx object with new instead, and provide the pattern and modifiers with strings;

var re = new RegExp("\\[.*?\\]", "g");
raina77ow
  • 103,633
  • 15
  • 192
  • 229
Björn
  • 29,019
  • 9
  • 65
  • 81
3

Splitting string into pattern and modifiers.

function getRegFromString(string){

     var a = string.split("/");
     modifiers= a.pop(); a.shift();
     pattern = a.join("/");
     return new RegExp(pattern, modifiers);
}
getRegFromString("/\[.*?\]/gim");
Anoop
  • 23,044
  • 10
  • 62
  • 76
-1
var string = "/\[.*?\]/g";
var regex = new RegExp(string);

ll work normaly.

PierrickP
  • 107
  • 7