Created
April 3, 2011 06:26
-
-
Save markmarkoh/900237 to your computer and use it in GitHub Desktop.
Javascript Regex Shorthand trick
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
| //In Javascript, a Regex object can be called like a function | |
| //like: /test/("is test in here") | |
| searchText = "padding 1234 rocket str austin TX 78704 more padding" | |
| /\d+.+\n{0,2}.+\s+[A-Z]{2}\s+\d{5}/m(searchText) | |
| //returns: ["1234 rocket str austin TX 78704"] | |
| //As opposed to the more verbose(but sometimes more appropriate in cases that you are reusing the Regex): | |
| var re = new RegExp(/\d+.+\n{0,2}.+\s+[A-Z]{2}\s+\d{5}/m); | |
| re.exec(searchText); | |
| //returns: ["1234 rocket str austin TX 78704"] | |
| //Neat! | |
| //From Secrets of the Javascript Ninja by John Resig |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment