Skip to content
FP

Faris Poljcic

1 article

March 2, 2022

Regular Expressions (Regex) In JavaScript

Software Development

Regular Expressions (Regex) In JavaScript

Regular Expressions (or regex for short) represent a sequence of characters used to define a search pattern. The two most common use cases where you would want to use regex are validating input and searching through text. Regex syntax can be intimidating, but learning the basics can help you understand much more complex patterns. Creating a regex The first thing you need to learn is how to create a regular expression. In JavaScript, a regular expression can be created in two ways: Using forward slashes const regex = /expression/flags 2. Using ​​RegExp object constructor const regex = new RegExp('expression', 'flags') The first syntax is cleaner and can improve performance, but if your regex expression is dynamic, meaning it can change over time or depend on some user input, you need to use the second syntax. The flags part of the expression will be explained below. Writing a regex You’ve just created a regular expression, but what can you write inside? A regular expression is formed from regular characters or a combination of simple and special characters. You can find an exact match using regular characters, but the full power of regex comes after learning special characters. There are many special characters, but the most common would be: ^ start of a string $ end of a string \s - white space \d - digit \w - word character \S - not a white space \D - not a digit \W - not a word character . - any character * - 0 or more preceding characters + - 1 or more preceding characters ? -0 or 1 preceding character {m,n} - at least m, at most n occurrences of the preceding character | - logical or [abc] - range (a or b or c) [^abc] not in range (not a and not b and not c) [a-z] - character range from a to z [0-9] - number range from 0 to 9 If you want to use a special character like a regular character to find an exact match you can escape it using a backslash. In addition to the actual expression, you can define flags that allow you to do advanced searching. For example, if you want to check for all matches and not only the first one you can use the g flag. If you want to use case-insensitive search use the i flag. If you want multi-line search use the m flag and so on. These flags can be used separately or together in any order. Let’s see these in an example. Let’s say you’re building a web application and you have a registration form. The user first enters a username which you need to validate. You first want the username to be at least 3 characters so you write: /^.{3,}$/ ^ matches the beginning of the string. Then comes .{3,} that represents any character 3 or more times. Finally, $ means the end of the string. But you figure out that you don’t want users to have usernames with unlimited characters, let’s limit the number of characters to 16. /^.{3,16}$/ Seems good, but then we have usernames that look like this 3.??,@= so you decide to limit the characters to lowercase letters, numbers, or dashes. /^[a-z0-9_-]{3,16}$/ Finally, you’re okay with users using upper case characters so you add a case-insensitive i flag to the end. /^[a-z0-9_-]{3,16}$/i And now you have a compact regular expression you can use anywhere for username validation. Using a regex in JavaScript After you’ve learned how to create and build a regular expression it’s time to use it. Using a regex differs from language to language, but in JavaScript the three most common functions would be: test () - checks if a pattern is present in a string, returns true or false /a|b/.test('car') // returns true 2. match() - checks matches in a string, returns an array containing all matches or null if none are found 'Quick Brown Fox'.match(/[A-Z]/g) // returns ['Q', 'B', 'F'] 3. search () - checks for a pattern match in a string, returns the index of the first match or -1 if not found 'Brown Fox'.search(/o/) // returns 2 These would be the basics of regular expressions and knowing them will be a great addition to your skills. If you want to learn more you can use tools like regexr or regex101 which let you interactively test your regular expressions and provide a detailed explanation of each regex element. "Regular Expressions (Regex) In JavaScript" Tech Bite was brought to you by Faris Poljčić, Software Engineer at Atlantbh. (more…)

Ready to Achieve More?

We’ll help you reach your goals quickly with an easy and straightforward process to kick off our collaboration. Here’s what happens next.

STEP 1

Discovery Call

Let’s chat to understand your company, project needs, and answer any questions along the way.

STEP 2

Free Consultation

Work closely with our experts to explore the right solutions for your business.

STEP 3

Collaboration Proposal

We'll recommend the best strategy for your goals, ensuring you get the most from our expertise.

STEP 4

30-Day Cancellation
Policy Contract

Spoiler: It’s Never Been Used

Enjoy peace of mind while we deliver excellence from day one—our track record speaks for itself.

Services you're interested in (Optional)