Write Tests for Regex!
This might be a no-brainer for some, but I just wanted to share this because of the many times I've been burned for being lazy or dumb. It's really not hard. You don't even need a testing framework. Just think of a list of things that should match and things that shouldn't. Make an HTML file with a <script>
tag and a list of:
if (!myRegex.test('somethingthatshouldmatch')) console.log("FAILURE");
if (myRegex.test('somethingthatshouldNOTmatch')) console.log("FAILURE");
Open in a browser, watch the console, and look for failures. If you find something new in the future, add it to the list and change your regex. You'll not only be able to test your new regex on the new case, but ensure it didn't break any of the old ones.
Written by Nathan Williford
Related protips
1 Response
Great point. Even better, use any of the great JS unit test frameworks out there. I find QUnit to be extremely quick and simple for testing functions like these.
test("somethingthatshouldmatch", function () {
var input = "somethingthatshouldmatch";
ok(myRegex.test(input) === true);
});
test("somethingthatshouldNOTmatch", function () {
var input = "somethingthatshouldNOTmatch";
ok(myRegex.test(input) === false);
});
Demo of a similar situation @ http://jsfiddle.net/stevejansen/nfUb6/