(Pssst! All the code referenced in this post can be found in https://github.com/NerdcoreSteve/regular-expressions. Pass it on!)
Match Beginning or Ending
^ character matches the beginning of a string, the
$ character matches the end of a string. If you have a regex that begins with a
^ and ends with a
$ then the entire string has to match your pattern or not at all.
console.log( 'Potatoes are my friends, potatoes are my family.' .match(/^potatoes/gi))
[ 'Potatoes' ]
console.log( 'Family Ties is a good show, but I prefer All In the Family.' .match(/family.$/gi))
[ 'Family.' ]
console.log( 'The Magic School Bus was a great show, but they really should have asked that kid\'s parents before driving through his digestive system' .match(/bu/gi))
[ 'Bu', 'bu' ]
console.log( 'The Magic School Bus was a great show, but they really should have asked that kid\'s parents before driving through his digestive system' .match(/^bu$/gi))
Regex-land has some really useful short-hand patterns:
console.log( 'A baker\'s dozen is 13. Why is that?' .match(/\d+/g))
[ '13' ]
\d matches any digit, the exact same thing as
\w matches any word character, the same thing as
\W matches any non-word character, which includes spaces and punctuation (among other things).
\s matches white space. There are even more, but, well, this series is already massive, so I'll leave it to you to google for them. :)
This or That
What if I want to match something or something else?
console.log( 'It was the best of times. It was the worst of times' .match(/(best|worst)/g))
[ 'best', 'worst' ]
Just wrap the things you want to match in parentheses and separate them with a
|. You can do as many as you want:
console.log( 'Twas bryllyg, and ye slythy toves Did gyre and gymble in ye wabe' .match(/(bryllyg|slythy|toves|gyre)/g))
[ 'bryllyg', 'slythy', 'toves', 'gyre' ]
Move on to part 4!