Regular Expressions in Javascript (Part 1): A Beginner's Guide.

·

2 min read

The first time I came across a Regular Expression, my brain did a freeze, pause, backflip, and thaw. Okay, I am probably exaggerating, but I did find it a bit overwhelming. This article attempts to put Regular expressions in simple terms.

What is a Regular Expression?

A Regular Expression, also called "Regex" is a series of characters that form or generate a search pattern. Think of it as a Hogwarts sorting hat, but for strings and texts. Regexes are used to perform text search and text replacement operations. In Javascript, Regexes are often used with the search() and replace() string methods.

A Typical Regex Body

There are certain structures that make up a typical Regular Expression. These parts are simple alphabets, texts, or special characters enclosed between backward slashes. These slashes tell Javascript that the characters enclosed are Regexes. They act just like quotes for strings. There are two methods for writing Regular expressions, I prefer the short version which is written below.

var regEx = /pattern/modifiers;

Pattern: This is a string that contains either alphabets or special characters, or a combination of both. They make up the specific search pattern you intend to run through your string. For example;

var meal = /beans/i;

The Above line of code specifies that any string that calls the "meal" regex in a search method, should find specifically where the word "beans" appears in the string.

Modifiers: These are also called Flags. These are single special characters that modify the search patterns between the slashes. There are six of them in javascript and are listed below.

1. i: This modifier makes the pattern search case insensitive. Hence beans is the same as **BeaNS ** and so on.

2. g: This modifies the search to look for all matches, without it – only the first match in the pattern, is returned.

I literally have to stop here because I have been procrastinating on sending this out. Part two comes shortly.

To Be Continued.....