Here are some notes I took while watching freeCodeCamp’s video covering covering regular expressions for JavaScript.

Online JavaScript Console

Regular Expressions

  • Define a search pattern that can be used to search for things in a string

Using the Test Method

  • takes a regex, applies it to a string and returns True or False based on whether the pattern matches something
let sentence = "The dog chased the cat."
// Do not need quote marks in the regex
let regex = /the/

let myString = "Hello, World!";
let myRegex = /Hello/;
// Use test method
// should return true
let result = myRegex.test(myString);

Match Literal Strings

let waldoIsHiding = "Somewhere Waldo is hiding in this text.";
// Case sensitive
let waldoRegex = /Waldo/;
let result = waldoRegex.test(waldoIsHiding);

Match a Literal String with Different Possibilities

let petString = "James has a pet cat.";
// Look for the words dog, cat, bird, or fish
let petRegex = /dog|cat|bird|fish/;
// Should return true as cat is present
let result = petRegex.test(petString);

Ignore Case While Matching

let myString = "freeCodeCamp";
// Ignores case when looking for matches
let fccRegex = /freecodecamp/i;
let result = fccRegex.test(myString);

Extract Matches

let extractStr = "Extract the word 'coding' from this string.";
let codingRegex = /coding/;
// Extracts the substring matching the provided regex
let result = extractStr.match(codingRegex);


Find More Than the First Match

let testStr = "Repeat, Repeat, Repeat";
// Adding the g flag will find every occurrence
let ourRegex = /Repeat/g;
let result1 = testStr.match(ourRegex);

let twinkleStar = "Twinkle, twinkle, little star";
// Will ignore case ***and*** find every occurrence
let starRegex = /twinkle/ig;
let result2 = twinkleStar.match(starRegex);


Match Anything with Wildcard Period

let humStr = "I'll hum a song";
let hugStr = "Bear hug";
let huRegex = /hu./;
// Matches any words that start with "hu"
// Matches any words that start with "hu"

let exampleStr = "Let's have run with regular expressions!";
// Match any word ending with "un"
let unRegex = /.un/;
let result = unRegex.test(exampleStr);

Match Single Character with Multiple Possibilities

// Matches "bag", "big", "bug"
let bgRegex = /b[aiu]g/;

let quoteSample = "Beware of bugs in the code; I have only proved it corr";
// Matches every vowel and ignores case
let vowelRegex = /[aeiou]/ig;
let result = quoteSample.match(vowelRegex);


Match Letters of the Alphabet

let quoteSample = "The quick brown fox jumped over the lazy dog.";
let alphabetRegex = /[a-z]/ig;
let result = quoteSample.match(alphabetRegex);


Match Numbers and Letters of the Alphabet

let quotsample = "Blueberry 3.141592653s are delicious.";

// Match any digits in range [1-9]
// Also match any letters "a" through "s" and ignore case 
let myRegex = /[a-s|2-6]/ig;

Match Single Characters Not Specified

let quoteSample = "3 blind mice.";
// Match any characters not containing
// numbers or vowels
let myRegex = /[^0-9aeiou]/ig;

Match Characters that Occur One or More Times

let difficultSpelling = "Mississippi";
// Match any occurence of the letter "s" one or more times
let myRegex = /s+/g;

Match Characters that Occur Zero or More Times

let soccerWord = "gooooooooal!";
let gPhrase = "gut feeling";
let oPhrase = "over the moon";
let goRegex = /go*/;
// Returns ["goooooooo"]
// Returns ["g"]
// Retrurns null

let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!";
// Match "a" zero or one times
let chewieRegex = /Aa*/;

Find Characters with Lazy Matching

  • greedy match: finds the longest possible part of a string that fits the regex pattern
    • regex patterns default to greedy
  • lazy match: finds the smallest part of the string that fits the regex pattern
let string = "titanic";
// Looks for words that start with "t" followed by zero or more letters and ends with "i"
// Adding a "?" makes it a lazy match 
let regex = /t[a-z]*?i/;

let text = "<h1>Winter is coming</h1>";
// Looks for a substring starting with "<" followed zero or more characters and ends with ">"
// Lazy match
let myRegex = /<.*?>/;

Find One or More Criminals in a Hunt

let crowd = 'P1P2P3P4P5P6PCCCP7P8P8';
// Matches one or more instances of "C"
let reCriminals = /C+/;

Match Beginning String Patterns

let rickyAndCal = "Cal and Ricky both like racing.";
// Match string that starts with "Cal"
let calRegex = /^Cal/;

Match Ending String Patterns

let caboose = "The last car on a train is the caboose";
// Match string that ends with "caboose"
let lastRegex = /caboose$/;

Match All Letters and Numbers

let quoteSample = "The five boxing wizards jump quickly";
// \w: Shorthand for matching all letters, case insensitive, all digits, and underscore
let alphabetRegexV2 = /\w/g;
let result = quoteSample.match(alphabetRegexV2);

Match Everything But Letters and Numbers

let quoteSample = "The five boxing wizards jump quickly.";
// \W: Shorthand for matching everything that is not a letter, digit, or underscore
let nonAlphatbetRegex = /\W/g;
let result = quoteSample.match(nonAlphatbetRegex);

Match All Numbers

let numString = "Your sandwich will be $5.00";
// \d: shorthand for matching all digits
let numRegex = /\d/g;
let result = numString.match(numRegex);

Match All Non-Numbers

let numString = "Your sandwich will be $5.00";
// \D: shorthand for matching all non digits
let noNumRegex = /\D/g;
let result = numString.match(noNumRegex);

Restrict Possible Usernames

1) If there are numbers, they must be at the end.
2) Letters can be lowercase and uppercase.
3) At least two characters long. Two-letter names can't have numbers.

let username = "JackOfAllTrades2";
// {2,}: number of times the previous pattern can match (two or more)
let userCheck = /^[A-za-z]{2,}\d*$/;

Match Whitespace

let sample = "Whitespace is important in separating words";
// Match all whitespace characters
let countWhiteSpace = /\s/g;

Match Non-Whitespace Characters

let sample = "Whitespace is important in separating words";
// Match all non-whitespace characters
let countNonWhiteSpace = /\S/g;

Specify Upper and Lower Number of Matches

let ohStr = "Ohhh no";
// Only match "Ohhh no" through "Ohhhhhh no"
let ohRegex = /Oh{3,6} no/;

Specify Only the Lower Number of Matches

let haStr = "Hazzzzah";
// Need to have at least four "z" after "Ha"
let haRegex = /Haz{4,}/;

Specify Exact Number of Matches

let timStr = "Timmmmber";
// Match exactly four "m" between "Ti" and "ber"
let timRegex = /Tim{4}ber/;

Check for All or None

let favWord = "favorite";
// Check for all or none instances of "u"
let favRegex = /favou?rite/;

Positive and Negative Lookahead

  • lookaheads: patterns that tell JavaScript to look ahead in your string to check for patterns further along. Can be useful when checking for multiple patterns over the same string.
let quit = "qu"
let noquit = "qt"
// Positive lookahead
// Looks for "q" makes sure "u" occurs later in the string 
let quRegex = /q(?=u)/;
// Negative lookahead
// Looks for "q" makes sure "u" does not occur later in the string
let qRegex = /q(?!u)/;
// Returns ["q"];
// Returns ["q"]

let sampleWord = "astro22naut";
// Match words that are greater than five characters and have two consecutive
let pwRegex = /(?=\w{5})(?=\D*\d{2})/;

Reuse Patterns Using Capture Groups

let repeatStr = "regex regex";
// Equivalent to /(\w+)\s(\w+)/
let repeatRegex = /(\w+)\s\1/;
// Returns true
// Returns ["regex regex", "regex"]

let repeatNum = "42 42 42";
// Equivalent to /(\d+)\s(\d+)\s(\d+)\s/
let reRegex = /^(\d+)\s\1\s\1$/;

Use Capture Groups to Search and Replace

let wrongText = "The sky is silver.";
let silverRegex = /silver/;
// Returns "The sky is blue."
console.log(wrongText.replace(silverRegex, "blue"));

// Returns "Camp Code"
// Matches two groups of characters separated by a whitespace
console.log("Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1'));

let huhText = "This sandwich is good.";
// Find the word "good"
let fixRegex = /good/;
// Replace it with "okey-dokey" 
let replaceText = "okey-dokey";
console.log(huhText.replace(fixRegex, replaceText));

Replace Whitespace from Start and End

let hello = "    Hello, World!  ";
let wsRegex = /^\s+|\s+$/g;
console.log(hello.replace(wsRegex, ""))