DEV Community

Cover image for An Intro To Regex's In Under 5 Minutes
Sandrico Provo
Sandrico Provo

Posted on

An Intro To Regex's In Under 5 Minutes

Regex stands for regular expression, and in JavaScript regex's give us the ability to match a string against a pattern that we've created. Some use cases for regex's would be making sure that user's enter a valid email on the front end, or making sure that some user input only contains letters instead of numbers. Regex's can be very useful in our JavaScript code, but how do we make them? Well, here is an example of a simple regex.

let myProfession = "Web Developer";
let professionRegex = /Web Developer/g;

if (professionRegex.test(myProfession)) console.log(true);
// console logs true
Enter fullscreen mode Exit fullscreen mode

The example above is a regex that tests whether or not the myProfession variable matches the professionRegex regex. This testing is done by the .test() method. This is a simple example, but with some imagination we can see how handy regex's can be. With that said, let's look at what goes into a regex and some different ways to make them!

Making A Regex

Basic Anatomy & Patterns

When you're writing a simple regex the basic parts of it are usually straight forward. Let's dissect our earlier example to see what goes into a regex.

let professionRegex = /Web Developer/g;
Enter fullscreen mode Exit fullscreen mode
Piece Description
/ This forward slash is the start of a regex, but you need to add the ending forward slash for JavaScript to know it's a regex.
Web Developer This is the regex content. You can add text or numbers here, but more commonly you add a pattern.
/ This is the ending forward slash of the regex.
g This is a flag at the end of the regex. It can modify how our regex's complete their search.

More Parts of a Regex

Now that we've seen a some basic regex anatomy, here are some common pieces that you could come across.

Symbol Description Example
^ This symbol tells the regex to search from the beginning of a string. /^Web Developer/g
\$ This symbol tells the regex to search from the end of a string. /^Web Developer/g
. This is like a wildcard, meaning it can match to any single character. /./g
\w This indicates any word. A capital W indicated any non-word character. /\w/g
\d This indicates any digit. A capital D indicated any non-digit character. /\d/g
[ ] Square brackets indicates a range. /[aA-zZ]/g
( ) Round brackets indicate a capture group. This means anything inside the brackets should be found together. /([aA-zZ]\
{ } This checks if something is repeated a number of times. /s{2}/g

Note: A vertical bar/pipe ( | ) indicates an or. An example for this would be: /\w|\d/g. This is here because markdown tables use | to indicate a new line and it couldn't be escaped properly.

Regex Literal Method

The regex literal method is the method we used to create our regex in the introduction example. It's created by using two forward slashes with a pattern in the middle. There are a ton of different patterns, but here are some basic examples to wet our feet with:

Using a pattern that checks for strings only we can test to see if our earlier example only contains strings.

let myProfession = "Web Developer";
let professionRegex = /[aA-zZ]/g;

if (professionRegex.test(myProfession)) console.log(true);
else console.log(false);
// console logs true
Enter fullscreen mode Exit fullscreen mode

Using a pattern that checks for numbers only we can test to see if our earlier example only contains numbers.

let myProfession = "Web Developer";
let professionRegex = /[0-9]/g;

if (professionRegex.test(myProfession)) console.log(true);
else console.log(false);
// console logs false
Enter fullscreen mode Exit fullscreen mode

Regex Constructor Method

To create a regex using the constructor method we need to initialize using the new keyword. This method is still a regex, but it has the advantage of letting us create dynamic regex's. Here is an example of what I mean.

let myProfession = "Web Developer";
let userInput = 29;
let professionRegex = new RegExp(`${userInput}`);

if (professionRegex.test(myProfession)) console.log(true);
else console.log(false);
// console logs false
Enter fullscreen mode Exit fullscreen mode

Thanks to the constructor method, we can combine template literals with regex's to make our tests more dynamic. An example use case for this combination could be when a variable you use for testing might be different depending on some user input or other code, and you would like this dynamic nature instead of hard coding for multiple scenarios.

Two Useful Methods to Know

Whenever we create a regex in JavaScript we also get default methods that we can use. These methods come from the JavaScript String Prototype, and they help us test our variables and inputs against our regex. There are more, but here are two methods I think are particular useful to know.

.test() Method

This method allows us to check whether or not the variable we are testing matches the regex we are testing it against. We've seen this method used in our code already, but let's look at it again to refresh our memories.

let myProfession = "Web Developer";
let professionRegex = /Web Developer/g;

if (professionRegex.test(myProfession)) console.log(true);
// console logs true
Enter fullscreen mode Exit fullscreen mode

.test() tells us if a variable matches our regex by returning true or false based on the test.

.match() Method

.match() is really cool! When used, it returns an array of whatever in the string matches the regex. Let's change our last example slightly to see .match() in action.

let myProfession = "Web Developer";
let professionRegex = /Web/g;

console.log(myProfession.match(professionRegex));
// console logs ["Web"]
Enter fullscreen mode Exit fullscreen mode

Using .match() gives us an array with the string "Web" inside because that is the part of the string that matches the regex. This could be quite useful when you are expecting a certain type of input from the user and you need to extract a piece from that input. Also, you may not have noticed but there is another difference when using .match(). When you are calling this method, you actually call it on the string instead of the regex! I've spent my fair share of time debugging that one so I hope this helps you save your time πŸ˜„.

Regex's Are Cool 😎

I hope that if you weren't already into regex's that now you can see how useful they can be when programming. We now know how to use a regex and can utilize the .test() and .match() methods, so hopefully you'll find a use for them in your next project!

Happy Learning πŸ˜„πŸ‘‹πŸΎ

Top comments (0)