Regular Expressions in JavaScript.

Regular Expressions in JavaScript.

Regular Expressions, popularly known as Regex, I think gets a bad rep for being tricky or especially difficult to understand or apply. It has been a muse for tech memes, but you don't always have to relate to all of that, this article is here to help you out.

What is a Regular Expression?

A regular expression is a sequence of characters that forms a search pattern. -w3schools

We use regular expressions to find a string or data using a search pattern to find what we are looking for.

Just as in different aspects of JavaScript Regex has it's specific methods that applies to it, these methods are explained in the paragraphs below.

Regular Expressions using the Test method:

The test method is a method in Regular expression (also known as Regex ) that returns a true or false value depending on if the string or pattern can or cannot be found.

Example:

let teststr = 'Way to go'; 
let testRegex =/Way/;
testRegex.test(testStr);  //returns true

The word(code) in the forward and backward slashes (the slash syntax is a way of creating a regular expression) is the word we are trying to find in the variable testStr, we then use the test method to find out if the word is present in the testRegex variable which to that it returns true.

Regular Expressions using the Match method:

The match method is a lot like the test method in that it finds whether the pattern is present in the given string or number except unlike the test method the match method extracts and not only checks the matches of the string.

Example:

 let matchStr = 'Regular Expressions';
let matchRegex = /Expressions/;
matchStr.match(matchRegex) //returns Expressions;

In the example above the match method checks and returns the matches of the string example. Notice how unlike the test method the match method takes the string to match for as a parameter.

Regular Expressions with the replace Method:

The replace method, as its name implies, 'replaces' a specified string with a different string or number.

Example:

var heyStr = "Hey now!";
var byeStr = "Bye";
var newStr = heyStr.replace("Hey", byeStr)//returns  "Bye now!";

Regular Expressions with the search Method:

The search method 'searches' within a string or number for a particular value specified and returns the position of the value.

Example:

var heyStr = "Hey now";
var res = heyStr.search("now")//returns 4;

Modifiers:

Regex has a wide range of modifiers each used for different purposes usually to aid the user to match a wider range of patterns with fewer pieces of code. Some of the most famous Regex flags are the g, I, etc. these flags are used to extract a pattern more than once (all its occurrence) and also used to make a word or letter case insensitive respectively.

The global modifier(g):

The global modifier(g) used outside the backslash in a Regex is used to extract all the occurrences of the string literal of number. The examples before the global example showed us how to test for and extract a given string that appeared once, and to return it once, which can be especially stressful and problematic when testing for string appearing multiple times thankfully the global modifier is here to help.

Example:

let testStr = 'Shake, Shake, Shake into the fire';
let  shakeStr = /Shake/g;
let testStr.match(shakeStr)//returns ['Shake', 'Shake', 'Shake'];

The example above tries to match the string ‘Shake’ in the testStr variable which it does as we’ve learned before except this time the g symbol extracts all the occurrences of ‘Shake’ and puts them in an array.

The Case Insensitive(i):

The case insensitive modifier, just as its name implies, allows the test, or match method to check or extract a string or pattern no matter the case it is in(either uppercase or lowercase).

Example:

let testStr = 'Hey now';
let heyStr = /hey/i;
testStr.match(heyStr) //returns  Hey;

As we can see from the example above the string to test for ‘hey’ has its first letter 'h' written in lowercase instead of uppercase and it still matches the testStr string, ‘Hey’.

Regular Expression Patterns:

The dot(.):

Sometimes when we try to match a string we don’t know all the characters we are trying to test for we use the dot symbol to help us out.

Example:

let  carRegex = 'I bought a new car';
let canRegex = 'It came in a can';
let caRegex = /ca./;
caRegex.test(carRegex)//returns true;
caRegex.test(canRegex) //returns true;

In the example above, the dot tests for words starting with 'ca'.

The Caret (^) used in array brackets:

This caret symbol used inside an array bracket in between the slashes is used to state the characters we do not want to match.

Example:

let heyRegex = 'Hey';
let testRegex = /[^ey]/; 
heyRegex.match(testRegex) //returns H;

The Caret (^):

This symbol is used to test if the string can be found at the beginning of the word or sentence.

Example:

let askRegex = 'Can I speak to you?';
let testRegex =  /^Ca/;
testRegex.test(askRegex)//returns true;

The dollar sign($):

The dollar sign used at the back of a string is used to check if the string can be found at the end of a word or sentence.

Example:

let askRegex = 'Can I speak to you?';
let testRegex =  /you$/;
testRegex.test(askRegex)//returns true;

Metacharacters:

These are characters with special meaning examples:

  • /\w/: This is used to test for alphanumeric symbols.
  • /\W/: This is used to test for non-alphanumeric symbols.
  • /\d/: This is used to test for digits only in a string or a group of numbers.
  • /\D/: This is used to test or match non-digits.
  • /\s/: This is used to match for whitespaces.
  • /\S/: This is used to match for non-whitespace non-whitespaces.