50 likes | 195 Views
Post-Module JavaScript. BTM 395: Internet Programming. Regular expressions (regex). Search and replace on steroids Lets you search for any kind of text, even with variable content Includes variables (back-references) for dynamic replacements
E N D
Post-Module JavaScript BTM 395: Internet Programming
Regular expressions (regex) • Search and replace on steroids • Lets you search for any kind of text, even with variable content • Includes variables (back-references) for dynamic replacements • Available in virtually every programming language, most text editors, and even Microsoft Word (called wildcards)
Regex in JavaScript • All JavaScript strings support the following functions: • match() returns an array of matched substrings • search() returns the position of the first match • replace() returns the new string with replaced text • JavaScript also has a special RegExp object
Learning regex • Best online resource and tutorials: http://www.regular-expressions.info • Online playground: http://gskinner.com/RegExr/ • Exercises: http://regex.sketchengine.co.uk/
Basic steps for creating a regex pattern • Define very clearly which kinds of text you want to match • Define very clearly which kinds of text you do NOT want to match • This step is optional if you are creating a quick and dirty solution • This step is essential if you are creating a solution that will treat uncertain user input • Experiment with sample text (both of what you want and of what you don’t want) until you get the right pattern • An online regex tool can help