Skip to content

Instantly share code, notes, and snippets.

@joshed-io
Created April 27, 2011 00:19
Show Gist options
  • Save joshed-io/943471 to your computer and use it in GitHub Desktop.
Save joshed-io/943471 to your computer and use it in GitHub Desktop.
Regular expression to determine if a string contains a valid regular expression
var regexpMatcher = /^\/([^\/]|\\\/)+\/[$gim]*$/;
function assert(value) { return regexpMatcher.test(value); }
function isRegexp(value) { if (!assert(value)) alert("Failed " + value); }
function isNotRegexp(value) { if (assert(value)) alert("Failed " + value); }
isRegexp("/foo/");
isRegexp("/foo/gim");
isRegexp("/foo/img");
isRegexp("/snacks\\/clif/"); // which as literal is just /snacks\/clif/
// and as an Object new RegExp("snacks/clif")
isNotRegexp("//");
isNotRegexp("/foo/b");
isNotRegexp("/foo/bar/baz/");
isNotRegexp("/foo/bar");
isNotRegexp("///");
alert("Silence is golden!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment