Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Javascript Regex Question

Hey all,

I'm trying to do a "replace" in javascript.  From what I understand, this must be done with a regex as follows:
// works fine:
        function dispEncodeString(x){
            data = x;
            var re = /</g;
            data = data.replace(re,"&lt;");
            re = />/g;
            data = data.replace(re,"&gt;");
            return data;        
        }

I run into problems when I try to initialize the regex from a variable instead of a literal /regex/ syntax, however:

// snippet:
var match = "";
match = "/test/";
mystring.replace(match, "newtext");

Can anyone help?

David Seruyange
Tuesday, December 14, 2004

From memory, something like:
match = /test/ig;
and
match = new RegExp("/test/", "ig");
are equivalent.

Joe
Tuesday, December 14, 2004

Thank you.  Passing the variable to the RegExp constructor idd work.

David Seruyange
Tuesday, December 14, 2004

the expression to search in regular expression when stored in a javascript variable should not be enclosed in quotes

so '/test/'  should be /test/  instead.

benoy narayanan
Wednesday, December 15, 2004

*  Recent Topics

*  Fog Creek Home