Fork me on GitHub

30 days of
MooTools


30 days of MooTools is a collection of tutorials to learn to use the MooTools javascrit library, first published in 2008 by ConsiderOpen.

The lessons are actually 23, as they where interrupted after this day.

As the original site is currently offline, the tutorials have been collected using the Wayback Machine to make them available to everyone interested in learning to use MooTools.

The tutorials are based on MooTools 1.2 so some parts could be deprecated and they should be updated and expanded based on the new MooTools versions.

The copyright (and gratitude) for the original lessons is hold by ConsiderOpen.




Idea Paolo Manganiello. Licence CC 3.0.

Mootools and Regular Expressions

If you haven’t already, I’d suggest checking out the rest of the 30 Days of Mootools Tutorials before continuing on. For day 13, we’ll do a brief overview of regular expressions, then look at the functionality Mootools offers to make life easier when dealing with them.

For those of you not already familiar with how a regular expression (regex) works, I highly suggest you spend some quality time with the reference links scattered in the text, and especially the “To Learn More” links at the bottom of this page.

We’re going to be looking at some extremely basic uses of regexes, there’s an incredible amount that they can do beyond what we’ll be talking about today.

The Basics

test()

At it’s simplest, a regular expression can be simply a string of text you wish to match. While javascript already provides a RegExp object with it’s own test() function, the Mootools test() function is a much friendlier and far less painful way to utilize regexes in javascript.

For starters, lets take a look at the simplest usage of test(), finding a specific string within a larger string :

//The string we'll be looking for a match in
var string_to_test = "Match anything in here";
 
//The regular expression we're looking for
var regular_expression = "anything";
 
//Apply the regular expression, returns either true or false
var result = string_to_test.test(regular_expression);
 
//result is now equal to true

This is essentially the same behavior you’d get from the contains() function, but where contains looks for complete words, the regular expression matches any occurrences of the regular expression. For example, contains() will not return true in this instance while test() will:

var string_to_match = "anything";
 
//Returns False
string_to_match.contains('nything')
 
//Returns True
string_to_match.test('nything');

Also, be aware that unless you explicitly tell it not to, the regex is case sensitive, so searching for “match” when the string contains “Match” will return false. You can play around with it below.

var regex_demo = function(){
	var test_string = $('regex_1_value').get('value');
	var regex_value = $('regex_1_match').get('value');
	var test_result = test_string.test(regex_value);

	if  (test_result){
		$('regex_1_result').set('html', "matched");
	} else {
		$('regex_1_result').set('html', "didn't match");
	}
}

Note that there are special characters in regular expressions that you have to be careful about using. If you place any of the following into regex box you may cause an error and have to reload this page for the demos to function.

- . * + ? ^ $ { } ( ) | [ ] / \
String to Test
Regular Expression
 

Ignoring Case

There are plenty of situations in which you aren’t concerned about the case of the term you are trying to match. If you don’t want a regular expression to be case sensitive, you can call test with the “i” parameter:

//The string we'll be looking for a match in
var string_to_test = "IgNorE CaSe";
 
//returns false
string_to_test.test("ignore");
 
//returns true
string_to_test.test("ignore", "i");

Technically speaking, you can pass multiple parameters to test, but since javascript currently only supports 3 regular expression parameters (2 of which are enabled by default in test()), the “i” parameter is probably the only thing you’ll be passing it for the time being. You can go ahead and test out the difference in case matching below :

var regex_demo = function(){
	//Get the string to test from the input field
	var test_string = $('regex_2_value').get('value');

	//Get the regular expression to use from the input field
	var regex_value = $('regex_2_match').get('value');

	//See if we're ignoring case sensitivity
	var regex_param = "";
	if ($('regex_2_param').checked){
		regex_param = "i";
	}

	//Run the test and get the result
	var test_result = test_string.test(regex_value, regex_param);

	//Update the result span with the what happened
	if (test_result){
		$('regex_2_result').set('html', "matched");
	} else {
		$('regex_2_result').set('html', "didn't match");
	}
}
String to Test
Regular Expression
Ignore Case
 

The Fun Stuff

Now that we’ve covered simple matching, we can start looking at some of the more impressive aspects of regexes. This doesn’t come close to covering everything possible with regexes—it’s a cherrypicking of some of the more immediately useful functionality.

Match at the beginning with ^

The regex ‘^’ operator allows you to look for a match at the beginning of a line regardless of whether the string you’re looking for exists later on in the string. Place it before the expression you want to match like so :

//The string we're going to test
var string_to_test = "lets match at the beginning"
 
//Tests to see if the string begins with lets, returns true
var is_true = string_to_test.match("^lets");

As you may expect, if the expression is not at the beginning of the string, this test will return false:

//The string we're going to test
var string_to_test = "lets match at the beginning";
 
//Tests to see if the string begins with match, returns false
var is_false = string_to_test.match("^match");

Go ahead and test it out below:

String to Test
Regular Expression
Ignore Case
 

Match at the end with $

The ‘$’ operator functions just like “^” with two differences.

  1. It matches at the end of a string instead of the beginning.
  2. It’s placed at the end of the expression instead of the beginning

Other than that, everything works as you would expect it to:

//The string we're going to test
var string_to_test = "lets match at the end";
 
//Tests to see if the string ends with end, returns true
var is_true = string_to_test.match("end$");

//Tests to see if the string ends with the, returns false
var is_false = string_to_test.match("the$");

One neat thing you can do with a combination of both these operators is test to see if a string contains just the expression you’re testing for and nothing else

//The string we're going to test
var string_to_test = "lets match everything";
 
//Tests to see if the string is precisely "lets match everything", returns true
var is_true = string_to_test.match("^lets match everything$");
 
//Tests to see if the string is precisely "lets everything", returns false
var is_false = string_to_test.match("^lets everything$");
String to Test
Regular Expression
Ignore Case
 

Character Classes

Character classes are another regex tool that allows you to match multiple specific characters (A or Z) as well as a range of characters (A through Z). If, for example, you want to test if either of the words moo or boo exist in a string, character classes allow you to do this by placing both characters in [brackets] within the regular expression :

//The string to test for moo
var first_string_to_test = "cows go moo";
 
//The string to test for boo
var second_string_to_test = "ghosts go boo";
 
//This matches the first but not the second
var returns_true = first_string_to_test.test("moo");
var returns_false = second_string_to_test("moo");
 
//This matches the second but not the first
returns_false = first_string_to_test.test("boo");
returns_true = second_string_to_test.test("boo")
 
//This matches both the second and the first
returns_true = first_string_to_test("[mb]oo");
returns_true = second_string_to_test("[mb]oo");
First string to test
 
Second string to test
 
Regular Expression
Ignore Case

In order to match a range of characters, you separate the beginning and the end of the range you’d like to match with a dash. You can define a range of either characters or numbers in the same way.

var string_to_test  = " b or 3";

//Match a, b, c, or d. Returns true
string_to_test.test("[a-d]");
 
//Match 1, 2, 3, 4, or 5. Returns true.
string_to_test.test("[1-5]");

If you’d like to match between multiple character classes, you can nest your character class calls inside their own [brackets] and seperate them with the ‘|’ operator

var string_to_test = "b or 3";
//Match a to d or 1 to 5, returns true
string_to_test.test([ [a-d] | [1-5] ]);
First string to test
 
Second string to test
 
Regular Expression
Ignore Case

escapeRegExp()

It may have occurred to you while reading that the way regular expressions are built could make matching some types of strings difficult. For instance, what if you wanted to look for [stuff-in-here] or $300 in a string? You can do so manually by placing a ‘\’ character before each special character you want to ignore.

//The string we want to match, note the [ ] - and $
var string_to_match = "[stuff-in-here] or $300";
 
//Incorrect way to match matching
string_to_match.test("[stuff-in-here]");
string_to_match.test("$300");
 
//Correct way to match,
//note the \ preceding the [ ] - and $
string_to_match.test("\[stuff\-in\-here\]");
string_to_match.test("\$300");

This can be a source of real headaches when dealing with regexes, especially if you’re not completely familiar with them. For reference, the special characters in regexes that require escaping are

- . * + ? ^ $ { } ( ) | [ ] / \

Fortunately, Mootools provides the escapeRegExp() function, which makes sure that your regexes are properly escaped. It’s another string function, so you can just call it on whatever string you want to match for before using it in your regular expression.

//The string we need to Escape
var unescaped_regex_string = "[stuff-in-here]";

//Escape the string
var escaped_regex_string = unescaped_regex_string.escapeRegExp();
 
//escaped_regex_string is "\[stuff\-in\-here\]"

Note this means that any special characters you want to use in your regular expression must be added on after the string has been escaped:

//The string we need to Escape
var unescaped_regex_string = "[stuff-in-here]“;

//Escape the string, matching at the beginning
var escaped_regex_string = “^” + unescaped_regex_string.escapeRegExp();

//escaped_regex_string is “^\[stuff\-in\-here\]”

Go ahead and check out the differences between using escapeRegExp() and not in the example below

var regex_demo = function(){
	//Get the string to test
	var test_string_1 = $('regex_7_value_1').get('value');

	//Get the regular expression to use
	var regex_value = $('regex_7_match').get('value');

	//Check to see if we're escaping regexes
	if ($('regex_7_escape').checked){
		//If so, escape the regex
		regex_value = regex_value.escapeRegExp();
	}

	//See if we're ignoring case sensitivity
	var regex_param = "";
	if ($('regex_7_param').checked){
		regex_param = "i";
	}

	//Run the test
	var test_result_1 = test_string_1.test(regex_value, regex_param);

	if (test_result_1){$('regex_7_result_1').set('html', "matched");}
	else {$('regex_7_result_1').set('html', "didn't match");}
}
First string to test
Regular Expression
use escapeRegExp()
Ignore Case
 

Remember that you can break the demos on this page by using unescaped special characters, so don’t be surprised if stuff stops working right after you’ve been playing with this.

To Learn More

Regular-Expressions.info is a good place to turn to for reference as well as learning—it’s a good site to spend some time with. For those of you familiar with Perl or who can deal with the language differences, the Section on Regexes in Roberts Perl Tutorial does a very good job of explaining the basic concepts. In the same vein, Stephen Ramsay has written a tutorial on Unix Regexes which goes over some of the concepts in a very clear and straightforward manner.

Another good place to check out is the Regex Library, they’ve got tons of examples of regular expressions to do all sorts of common tasks. Finally, if you’re getting brave you should spend some time with the Javascript Regular Expressions Reference from Mozilla. It can get pretty dense, but it’s incredibly useful. For information about the Mootools side of the equation, check out the test() Documentation

Tomorrow’s Tutorial

On day 14 we are going to look at periodical and have a look at using hashes in Mootools 1.2