Regular Expressions in JavaScript: An Introduction
By: Ross Bulat
Tags: JavaScript, Software Development, Software Engineering, Development, Programming

Regular Expressions in JavaScript: An Introduction

How to use Regex in JavaScript to validate and format strings

Regex in JavaScript: Your strings won’t know what hit them

JavaScript’s implementation of Regex is useful for a range of string validation, formatting and iteration techniques. This article acts as an introduction to using regular expressions in JavaScript, touching on useful ways to use them, in addition to exploring some of the cryptic-like syntax that regular expressions entail. Rather than attempting to be a comprehensive guide for all Regex features, this piece instead focuses on super-useful concepts and real-world examples to get you started using Regex in your JavaScript apps.

Regular expressions are notably hard to read as they gain in complexity, where it is necessary for the developer to have some knowledge of Regex syntax to know what is being tested.

One can summarise regular expressions as patterns used to match character combinations in strings.

JavaScript supports regular expressions in a range of its native APIs such as match , matchAll , replace , among others, for testing a string against the defined pattern via the regular expression. Perhaps the most basic type of support is the Regex object, that tests whether a pattern is present within a string with its built-in methods such as exec() and test() .

To demonstrate Regex in its simplest form, we can check whether a particular substring pattern is present against another string to test against with Regex’s test() , that will return a boolean. This is how we’d test whether the string word is present within a string — there are actually two ways we can do this, here’s the first:

// the simplest use case of Regex: substring testing const str = "How many words will this article have?";

const result = new RegExp('word').test(str);

JavaScript also recognises a regular expression simply by wrapping it in forward slashes:

const result2 = /word/.test(str);

This cleaner syntax will be used for the rest of this article.

This simple use case of Regex is useful for testing form values or validating other unknown data. You could indeed use this method as a simple way to test things like secure URLs, where you expect https:// within the string. However, as we all know, a valid URL has a few more rules than this — a domain suffix, an optional www. , a lack of whitespace, support for a limited amount of special characters, etc.

This is where Regex shines — it can check all these attributes in one regular expression, or “pattern”, being able to test very complex strings that have an arbitrary number of patterns within them.

Matching one of several Characters with Character Classes

The English language has quite a few arbitrary words with the potential to be a nightmare for form validation — if it was not for regular expressions. Take the word color that is also correctly spelled as colour, or adapter and adaptor, ambience and ambiance — the list continues. This is where Character Classes, also termed Character Sets, come in handy with Regex.

They are defined with square brackets followed by a range of acceptable characters in that position. Let’s take ambience and ambiance — this is how we’d test both words:

const str = "This office has a pleasant ambience";

const result = /ambi[ae]nce/.test(str);

The above character class accepts either an e or a as the 5th character of the tested string.

Testing for optional characters

Testing color and colour is slightly different — there is actually an additional optional character, being the u. Consider the following regular expression, that checks for the optional character:

const str = "How many colours are there in a rainbow?";

const result = /colou?r/.test(str);

Notice the ? after the u character — this introduces the first operator of this talk. The ? operator declares a character or group of characters as optional in the defined pattern. colour is indeed present within str , and test() will return true .

Take a scenario where we need to test a string representing a month, that could be displayed in short-form or long-form, such as Jan or January. Both are valid months, but the uary characters can be omitted in the short form.

To test this, we can wrap multiple characters in parenthesis, also termed a Capturing Group, and make the entire group optional.

const str = "January 3rd is my birthday?";

const result = /[Jj]an(uary)?/.test(str);

Note that we’re accepting both upper and lower case j, and have declared an optional capturing group with (uary)? .

There are more efficient ways to test character cases that we’ll discover further down.

We can also test a range of characters in a character class. A dash (-) between two characters present a range. For example, you may with to validate a hexadecimal string, such as when you have a visual editor in the browser to toggle colours. Check out the following regular expression to do this, that introduces more syntax to our Regex endeavours:

const str = "ff0000"; //red const result = /[0-9A-F]{6}/i.test(str);

The ranges of 0–9 and A-F are searched, along with curly braces with a 6 in-between. {6} here is declaring that the pattern should match exactly 6 times within the string being tested. This makes sense, as a hexadecimal value is 6 characters in length.

Also of interest is the i character included at the end of the regular expression , after the closing forward slash — what is this?

Introducing Flags

i is one of several flags available to use at the end of a regular expression. The i flag makes the search case-insensitive, so both upper case and lower case A-F are searched. Our character class searches for the range of A-F, but with the i flag, a-f is also searched. There is no need to define both with [0-9A-Fa-f] .

Another commonly used flag is g , that searches for all matches within a string. Up til now, we have only explored single matching regular expressions. Moving forward, we will want to search all matches within a string, making Regex a much more powerful concept for processing larger bulks of text.

Negating Character Classes with ^

We can also define a Character Class that you do not wish to match within a string.

If we took the above example and did not wish to match hexadecimal strings, the caret (^) can be placed at the beginning of the Character Class:

const result = /[^0-9A-F]{6}/i.test(str);

The result will now consequently return false in the event a hexadecimal string is present.

Negated Character Classes are effective for defining what you don’t want to appear within a pattern, and may come in handy in forms of validation, such as testing for sensitive words and phrases in a user-submitted comment.

Before we continue, let’s recap the terms explored so far:

Character Classes / Character Sets: Using the square brackets to define a range of possible characters in an expression.

Using the square brackets to define a range of possible characters in an expression. Operators with ? for optional characters within a regular expression.

with for optional characters within a regular expression. Capturing Groups that are defined with parenthesis, allowing us to test a group of characters, or a subset of a string.

that are defined with parenthesis, allowing us to test a group of characters, or a subset of a string. Flags: “global” level configurations that manipulate the Regex search in some way.

The next set of examples will level up our understanding of Regex, using them in a global fashion to tackle more real-world problems.