"lwoods" <la***@lwoods.com> wrote
I am trying to use a string for a regular expression pattern. Here is a
test that I set up:
var s="^\d{3}-\d{3}-\d{4}$";
var r=new RegExp();
r.compile(s);
var t="333-333-3333";
alert(r.test(t));
I have tried this with and without the "compile", and also adding the
"/..../" to the beginning and end of the string, but I always get "false".
Can you use a string to represent a pattern...in Javascript?
Yes, and as is usual with strings, it will look for and evaluate backslashes
which it thinks introduce an escaped meta-character in the next position. So
if you want your backslashes to even be seen by the regex interpreter, you
need to ... well, escape them. Try this:
var s="^\\d{3}-\\d{3}-\\d{4}$";
Every two backslahes become one backslash in the regex. Don't surround the
string with forward slashes. Given a string, the regexer will do that
itself.
--
hth
ivo
http://4umi.com/web/javascript/