Using Regular Expressions in JavaScript

Wesley Beck
CodeX
Published in
7 min readJun 19, 2021
Photo by Tudor Baciu on Unsplash

After completing my software engineering boot camp with Flatiron School, I was left with the feeling that “this is just the beginning, I still have much to learn.” While checking out websites that offered free learning curriculums to further my education, I decided to start on the JavaScript Data Structures and Algorithms certification hosted by freeCodeCamp so that I could further solidify my vanilla JavaScript skills, as well as learn more efficient methods to solve algorithms with the course. At the time of writing this, I am still working on said course, and after a little ways through, I stumbled upon Regex(Regular Expressions) that piqued my interest. During the first phase of the Flatiron boot camp, I learned just enough regex in Ruby to be able to create a method for my first project that would only accept numbers as an input to access a certain object instance from a class I created. JavaScript’s syntax and way seem much easier to understand and implement and with their built in methods its easy to evaluate if characters or numbers within a string or number will match or not(at least with my current knowledge).

There is actually a lot of documentation when it comes to using regular expressions, so I will just be going over some of the basics in this blog to highlight possible uses and some of the syntax to achieve the ideal output. I will post resources where you can learn more about regular expressions at the end of the of this post. Also note, I will be interchanging regex and regular expression throughout this post, however regular expressions can be referred to elsewhere as: regex, regexp, and regular expressions.

To get started, you can learn simple syntax:

You can code out all regular expressions by first wrapping the characters or words you either want or not want to match with a string you would be using the regex for like so:

/example/

You can set them as a variable in your code which you can do so in two ways:

Initializing and assigning a variable to what is called an expression literal (the literal regular expression):

let regex = /chars/;

Or you can use the class constructor function and pass in the argument of chars you want to evaluate as a string:

let regexTwo = new RegExp('chars');
regexTwo;
// /chars/

It’s best to use the latter operation for dynamic programming, where the regex to be evaluated can change (e.g. a user’s input).

From here, you can use a few different methods to test or match the pattern you want to evaluate with a string or value(number).

.test()

You can use regex and the built-in method of test() with regex to evaluate a whether a string has the characters or matches the characters depending on what special characters you use within your regex. Below is a basic example of using this method with regex and evaluating a string:

Using .test() returns a Boolean value.

With the .test() method, you first use the regex created and chain on the .text method and then pass the argument of the string you want to test. The .test() operation returns a Boolean (True or False), which could be helpful if you need to create a tight control flow in web app where input is recorded for example.

.match()

Rather than returning a Boolean value, .match() will actually return the part of the string that exactly matches your regular expression created. In the example below, I only targeted the character ‘r’, so it will return the first r in the string. Keep in mind that .match() will return an array. so be careful how you use it:

Using .match() returns an array of all instances that match the regular expression.

From my Chrome console snippet(my above example), I added two flags that allowed me to return all “r” characters from the string that was chained with .match(). Match is slightly different from test(), where rather than chaining the method onto the regex like with test(), you chain the method to the string/value you want to evaluate, and pass the regex as the argument to the match method. Also, without flags or explicit regular expression definition, if you utilize the .match() operation, it will return the first instance of the regex matching from the string you want evaluated.

If you notice in my above example, there were the letters gi attached at the end of my regular expression. The g and i are what are known as flags.

Flags are characters with special meaning that you can append to the end of your regex patterns to modify the behavior of how and what your regex pattern will return from a given string. The g flag used in the above example means “global.” This flag is used to match all patterns that occur within the string being evaluated. So, in my example above I created the pattern with just “r” in it, and when using the g flag, return all occurrences of the “r” character in the string, hence the array of four r’s that was returned.

Although it did not really apply to the example, the i flag appended was to ignore case specificity, thus it would have returned all the occurrences of r that were also capitalized in the previous example snippet(if there were any capitalized). These two flags seem to be common to use, however you can learn more about other flags here.

Another cool thing about regex that you might have questions about(if you don’t know about regex or how it works), is the ability to use consecutive groupings. What I mean by this, is that lets say you wanted to filter out any inputs with numbers in them. It would be long and messy to create a regex pattern that looks like this:

let numberPattern = /0123456789/;

You can actually create a sort of set pattern that you want using brackets [], and a dash/hyphen between (-), but the numbers/letters must increment from each other. Let’s say you had to find inputs that only matched number values. You could create a regex pattern like so:

let numberPat = /[0-9]/;

This syntax will signify a range and will be recognized as the pattern to match any numbers between 0 and 9. You can do this with letters as well, keeping in mind to use ranges that run from least to greatest values with numbers and then order by alphabet when using letters. This way looks much cleaner, and I find it easier to understand as well.

Special Characters in Regular Expressions

Now, that we have gone over some basics, learning about special characters you can use can help drastically with your pattern matching with regular expressions in JavaScript. Special characters are sometimes used within patterns to manipulate the actual pattern within the regular expression. An example I will give is with a group of strings that end in the same letters and start with different ones:

. (period) is a special character in which you can pattern match occurrences within a string where the words in a string might have the same words in order like a poem or rhyme:

let matchingWords = "Go to the bog in the fog and catch a frog";
matchingWords.match(/.og/g);

When executing the above code in my browser console here is the result:

match returned all instances where the string ends in ‘og’.

In this example, I made a mistake where my regex pattern was only looking for all matches where it matched three characters. the . accounted for only only 3 characters. To correct this we can use another special character, but we will have to remove the period.

The + special character accounts for issues like we had in the above example. Because the . is the wildcards character, it will looking for any character in the pattern position, even if it is a whitespace. So using the + character allows us call on a specific character, in this case a letter or letters, and modify the behavior of our regex pattern to read for one or more characters in at that position, so to speak:

Using the + character to match instances longer than 3 characters while ignoring whitespace.

This achieves the desired result of returning all instances that end in “og” correctly, unlike the previous example using the .(wildcard) character in our regular expression.

These are just a few examples of what can be done with regex, and there are many more complex methods and reasons to use regular expressions.

Please let me know what you think of my examples and explanations. I know there is a lot more that to cover on regular expressions, but I just wanted to share the basics and the power of regular expressions for individuals such as myself who may have known about regex who may be intimidated by it, or just genuinely have not had any practice with them. I hope this was helpful and I’ll have more resources posted below including a great cheat sheet that I came across while writing this. I’d love to hear thoughts or anything I could have done better, as well as things to go over for future blog ideas. Happy hacking!

Resources:

MDN -> Regular Expressions

CodeGauge -> Table of Regex Flags

Debuggex -> JS Regex Cheatsheet

--

--

Wesley Beck
CodeX
Writer for

Recent Flatiron Boot Camp Grad. Pursuing my dream to become a software engineer, sharing what I can to help others that are new to coding.