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.

0

3 Answers 3

13

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

var re = new RegExp("\\[.*?\\]", "g");
Sign up to request clarification or add additional context in comments.

2 Comments

oh thank you. I tried this one but I didn't know you had to remove the / around the regex. It works properly now, tackar :>
@raina77ow -- Thank's for the edit, I was too quick there...
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");

Comments

-2
var string = "/\[.*?\]/g";
var regex = new RegExp(string);

ll work normaly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.