What You Should Know About Regex

A few Useful Tips When Using Regular Expressions

Cedric Patton Jr
2 min readJan 25, 2021
Photo by davide ragusa on Unsplash

Regular expressions are used to search for various patterns within strings. Today I wanted to share a few tips to keep in mind when using regex.

Constructing a Regular Expression

Regular expressions can be constructed two ways: regex literal and constructor function.

Regex Literal ex.

let regex = /pattern/;

Constructor Function ex.

let regex = new RegExp(‘patte.nr’);

Methods

There are various methods that use regular expressions. The methods and their terms are referenced from develop.mozilla.org

exec()Executes a search for a match in a string. It returns an array of information or null on a mismatch.

test()Tests for a match in a string. It returns true or false.match()

Returns an array containing all of the matches, including capturing groups, or null if no match is found.

matchAll()Returns an iterator containing all of the matches, including capturing groups.

search()Tests for a match in a string. It returns the index of the match, or -1 if the search fails.

replace()Executes a search for a match in a string, and replaces the matched substring with a replacement substring.

replaceAll()Executes a search for all matches in a string, and replaces the matched substrings with a replacement substring.

split()Uses a regular expression or a fixed string to break a string into an array of substrings.

Flags and Special Characters

Both flags and special characters are used to create more specific regex search patterns. Flags go at the end of regular expressions right after the second forward slash if you are using the literal method, or you use a comma to create a second parameter when call the the constructor directly; Special charater are placed inside the pattern.

Regex Literal ex.

let regex = /pattern/flag;

Constructor Function ex.

let regex = new RegExp(‘pattern’ , ‘flag’);

Some common flags are: g, i, m, s, u, and y

Using Parenthesis

Parenthesis is used to recall a specific part of an regex pattern that can be used later.

Escaping

If you need to use a special character for its’ literal meaning, then you can make use of the backslash for this purpose. For example, if you want to use ‘*’ as a normal asterisk, you would do it like so: ‘\*’

--

--

Cedric Patton Jr

A coding and motorcycle enthusiast who’s passionate about personal development and learning. Recent Flatiron School of Software Engineering graduate.