If you’re new to regex, and want a bit of a quick intro
these slides
should help get you started.
So you’ve got your regex, what now? Here’s a quick tutorial of what you can
do with it. We’ll look at two useful ways of using regex in Javascript: test
and replace
Test
Let’s say you have a contact form that has a field for a reference number for your account
(say for a bank or utility service). The company’s reference numbers are expected in the form of
1000000AA
where A is any letter and 0 is any number. That could be described as:
"1, 6 numbers, 2 letters".
Try to regexcavate for that and you’ll get this:
/1[0-9]{6}[a-zA-Z]{2}/
Note: in Javascript you can define a regex literal by putting the expression between
/
characters. Regexcavate only gives you the expression, but we’re showing
you the Javascript notation for demonstration purposes.
So, how can this be used to check against user input? Well, we can use this pattern in
a little Javascript function like so:
var ref = document.getElementById('referenceNumber'); // the ID of reference number field
var regex = /1[0-9]{6}[a-zA-Z]{2}/; // the pattern we’re expecting
if ( regex.test(ref.value) ) {
// do stuff if match found
} else {
// show error messages about reference format
}
For more information on the Javascript test()
method, check out
MDN for Regexp.test
Replace
Matching a pattern is useful - especially for more complex things like email addresses,
usernames, phone numbers etc. but frequently you want to find and replace on a search
pattern.
If you are using a text editor like Textmate, Sublime Text or Vim, you’ll probably
find that it’s search and replace functionality will accept a regex as the search pattern.
This means you can find stuff that you would not normally be able to.
Let’s say you have some code that is littered with trailing whitespace. This can cause issues
in some languages but is just generally a bit messy to look at. Well, you could match all
whitespace at the end of a line and replace it with nothing to tidy things up.
Try to regexcavate for "any whitespaces, at the end of the line" and you’ll get this:
/\s+$/
Now use this in a find and replace, searching for \s+$
and "replace all" with
an empty field and you’ll be trailing whitespace free!
You can also use the String.replace()
method in Javascript. Here’s a quick
example... we're rather fond of regex, so let's update the string below:
var string = 'I hate regular expressions... hate them!';
string = string.replace(/hate/g, 'love'); // "g" replaces all occurrences
console.log(string); // 'I love regular expressions... love them!'