Simple Regex in JavaScript

Mateo Rey
3 min readJul 24, 2022

In JavaScript one of the most difficult challenges is understanding the pattern recognition due to its many flags and syntax rules that make it hard to read at first glance. Fortunately I have a compilation of most flags and syntax rules that you might run into when learning and using regex in JavaScript.

Regex in JavaScript is honed in on simplifying large parameters for functions, methods, or anything you can think of that takes arguments in JavaScript. For example sometimes you may run into the issue that you have to check if a string has letters inside of it. By using regex you can use the special .test() method, which only works with regex’s.

Now with ease you have a short and concise function without the hassle of typing out every alphanumeric character and cluttering your code. Additionally this same principle applies with numbers as well, inside of strings. Listed below is every default regex in JavaScript.

/\d/

Any digit character

/\w/

Any alphanumeric character (“word character”)

/\s/

Any whitespace character (space, tab, newline, and similar)

/\D/

Any character that is not a digit

/\W/

Any nonalphanumeric character

/\S/

Any nonwhitespace character

/./

Any character except for newline

Conveniently with regex’s you can search for an inversion pattern by adding the caret (^) within brackets around your regex. Such as this, /[^regex]/, and search if a parameter does not have the pattern.

Regex syntax introduces flags and operators that can be used to specify regex patterns. For example with the .replace() function, you are able to specifically replace the first occurrence or use /regex/g to replace every pattern occurrence.

First log without global flag, second includes global flag.

/regex+/

Adding plus says there may be more than one occurrence.

/’colou?r’/

Using the ‘?’ After a letter will make it optional for the match.

/regex{num}/

Curly braces allow for a number of occurrences to be allowed(useful for date

or checking a specific numerical combination).

/regex1(regex2)+/i

Allows for searches of multiple patterns with a plus at the end and second pattern in parenthesis. Lowercase ‘i’ demonstrates case insensitivity.

/^regex$/

The ^ before the expression specifies that the match must start with the regex and additionally with the $ at the end it enforces that the match must be the exact regex pattern.

/\bregex\b/

The \b goes before and after a regex when you are searching a string for a pattern which is separated by word boundaries, such as spaces or punctuation.

/(regex|regex)/

The | shows that it can be either pattern for the test.

Lastly, I would like to take note that these are simple methods with regex and uses as well. For a more challenging view on regex that combine the concepts in this article I would recommend you to try coding challenges with regex. Happy Coding.

--

--