JavaScript Regular Expressions

JavaScript Regular Expressions

Regular expressions (REGEX) are used to test for patterns in strings or check if they match a requirement you have set. In JavaScript, Regular expressions are also objects, therefore they have methods. Examples of these methods are test(), match(), matchAll(), replace() and some more.

For example, you want to check if you can find the word 'dog' in a sentence a user have submitted or you want to check if a user input matches the answer pattern you want, like in the case of an email address. These are examples of use cases for Regular Expressions. Let's get down to code examples.

The Test() Method

The first basic regex we will learn is the regex test. We gave a test for the user to use dog in a sentence and we want to find out if the user used the word dog in the sentence, we test for dog. A regex test returns true or false. Run this code in your console:

let stringInput = 'The dog is brown';
let regexTest = /dog/;
let result = regexTest.test(stringInput);
console.log(result);
// Result should return true as dog is in the stringInput .

// Observe how we did regexTest.test(stringInput)
// Note that the regexTest is put between two forward slashes //, JavaScript knows that it is a Regex.
// RegexTest is our regex, test is the method we are using and stringInput is the string we are testing
// Try testing for a sentence which does not include dog
// Also try testing for a sentence that has dog as Dog

Using Ignore Flag

If you change the dog to uppercase, the test returns false. The test is searching for a literal match in terms of the letter casing. If we want ignore the letter case, we have to use the ignore flag. the ignore flag is 'i'. We will see how to use it.

const caseIgnoreTest = /ignore/i;
const sample = 'IgNorE the case';
let result = caseIgnoreTest.test(sample);
console.log(result);
// This should return true as we are using the ignore 'i' flag, the test will pass irrespective of the case.

Using the OR operator '|'

Now lets's look at another example of regex tests. In this example we would be able to text for more than one word.

 const regex = /dog|cat/;
// Note the | between dog and cat. This is the 'or' operator.
// You can also include the ignore flag to ignore the letter case. /dog|cat/i;

let str = 'cat and rabbit';
let str2 = 'rabbit and dog';
let str3 = 'porcupine and armadillo';

console.log(regex.test(str));  // Should return true
console.log(regex.test(str2));  // Should return true
console.log(regex.test(str3));  // Should return false

// This test returns true when one of the word in the regex is present in the string we are testing

The Match() Method

We have performed Regex Tests so far, Now let's move on to Regex match. The Regex match() retrieves the result matching a string against a regular expression. Regex Match finds any word that matches a pattern that we have set. The syntax is string.match(Regular Expressions). To use the .match() method, apply the method on the string and pass the regex inside the parentheses.

const sample = "Hello Gambit the mutant";
const matchTest = /mutant/;
let ans = sample.match(matchTest);
console.log(ans);
// Should return ['mutant', index: 17, input: 'Hello Gambit the mutant', groups: undefined]

The Global Flag

The above example can only search or extract the pattern once after which it stops the search. To search for a pattern for more than once, we can use the global 'g' flag. This will search for all possible appearances of the pattern. Here is an example:

// To extract all the match we get, we use the g flag.
const sample = "Hello Gambito the mutant, Wolverine addresses gambling Gambit";
const matchTest = /Gambit/g;
let answer = sample.match(matchTest);
console.log(answer);
// should return ['Gambit', 'Gambit']; from Gambit-o and Gambit

This can be used together with the ignore flag 'i' and the OR operator | that we learnt earlier. Let' see an example:

// The global 'g' flag can be used together with the i flag (which ignore letter case)
const sample = "Turns the LeGs to jelly, said Thanos with strong legS.";
const repeatedWords = /legs/gi;
let ans = sample.match(repeatedWords);
console.log(ans);
// ans should return ['LeGs', 'legS'];

// Using the OR operator
let deadAvengers = "Widow, Thor, IronMan";
let deadAvengersTest = /widow|ironman|captain america/gi;
let result = deadAvengers .match(deadAvengersTest);
console.log(result);
// result should return ['widow', 'ironman'];

Single Character with Many Possibilities

We can also match a single character with many possibilities. What do I mean? We want to match for words such as cat, bat, rat but not goat or fat. Instead of writing individual regex for cat, rat and bat, we can use character classes '[ ]'. Since cat, rat and bat have 'at' in common, we will put the varying letters in the character class, [cbr] so our regex becomes '[cbr]at'; Let's try this in code

const regexTest = /[cbr]at/gi;
// remember the global and ignore flag
const testCat = "cat";
const testRat = "rat";
const testFat = "fat";
const testGoat = "goat";
const tetstAll = 'Goat, cat, fat rats and bat';

// Testing for rat
let RatResult = testRat.match(regexTest);
console.log(RatResult);
// should return ['rat'];

// Testing for fat
let FatResult = testFat.match(regexTest);
console.log(FatResult);
// should return null, as fat is not in our regex pattern

//  try testing for the remaining strings

Match Range of Alphabet and Number

To round up this first part of Javascript Regular Expressions we will look at matching ranges of alphabet and numbers. This is done using the hyphen ( - ). For example, we want to match the letters between a and j, our regex will look like /a-j/. You should use the global flag and you can add the ignore flag. The same syntax goes for matching a range of numbers.

//  You can use test method or match method, it's your choice!
const RangeRegex = /[a-k]at/gi;

const catString = 'cat';
const fatString = 'fat';
const ratString = 'rat';
const patString = 'pat';

RangeRegex.test(catString); // should return true as c is in the declared range
RangeRegex.test(fatString); // should return true as f is in the declared range
RangeRegex.test(patString); // should return false as p is not in the declared range
RangeRegex.test(ratString); // should return false as r is not in the declared range

This Topic will be continued in other posts. We will look at some more Regex basics and then examples of Regex use cases in real world applications.

Thanks for reading!!