Created
January 27, 2011 13:27
-
-
Save gabrielfalcao/798497 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.escapeToRegex = function (){ | |
var parts = []; | |
for (x=0;x<this.length;x++){parts.push("["+this[x]+"]");} | |
return parts.join(""); | |
} | |
String.prototype.escapeToRegexNegative = function (){ | |
var last = "", parts = []; | |
for (x=0;x<this.length;x++){ | |
parts.push(last.escapeToRegex() + "[^"+this[x]+"]"); | |
last += this[x]; | |
} | |
return "(" + parts.join("|") + "|^|$)"; | |
} | |
/* testing */ | |
var got = "gab".escapeToRegex(); | |
var expected = "[g][a][b]"; | |
if (got != expected) { | |
throw got + " should be equals to " + expected; | |
} | |
var got = "gab".escapeToRegexNegative(); | |
var expected = "([^g]|[g][^a]|[g][a][^b]|^|$)"; | |
if (got != expected) { | |
throw got + " should be equals to " + expected; | |
} | |
alert("all tests passed!"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cuidado que o x tá virando variável global boy