doug Posted July 20, 2009 Share Posted July 20, 2009 This truly is a simple regular expression question. :)I have a variable theTitle with the value: "Test Group A BTYZ311-1"And a variable courseCode with the value "BTYZ311".I want to see if theTitle contains courseCode followed by a dash followed by 1 or more digits.This is my test: var matchExp = new RegExp(courseCode + '\-\d+', "i");if (!matchExp.test(theTitle)) { // do something because theTitle doesn't seem to contain the courseCode plus dash + number} The problem is the .test() method always returns false, so there must be something wrong with my RegExp.Does anybody happen to see what that might be?Thanks,doug Link to comment Share on other sites More sharing options...
jeffman Posted July 20, 2009 Share Posted July 20, 2009 Alerting matchExp reveals the problem, and it's one of the reasons I never use the RegExp constructor. It's just counter-intuitive. Everything is fine except for your escape character, which needs to be escaped twice. So \\d+I think in this context that escaping the - character is not necessary. At least, it works for me in FF without being escaped. Link to comment Share on other sites More sharing options...
doug Posted July 21, 2009 Author Share Posted July 21, 2009 Alerting matchExp reveals the problem, and it's one of the reasons I never use the RegExp constructor. It's just counter-intuitive. Everything is fine except for your escape character, which needs to be escaped twice. So \\d+I think in this context that escaping the - character is not necessary. At least, it works for me in FF without being escaped.Thanks. That did work! I sort of see why and also don't see why. I thought that RegExp was supposed to take a string and turn it into a regular expression. \d only has one interpretation in a regular expression - a digit. So I thought that was ok as is. In fact, I would have guessed that \\d+ meant "find a backslash, the letter d and a plus sign."But anyway, I'll just try to remember to escape all my backslashes in RegExp from now on.You are right, of course, about \-, but I tend to escape all my punctuation so I don't have to remember which has special meaning and which doesn't.Thanks!doug Link to comment Share on other sites More sharing options...
justsomeguy Posted July 21, 2009 Share Posted July 21, 2009 The escaping is for Javascript, not the regexp. You need to escape slashes in Javascript strings. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.