Javascript Regex Cheatsheet



Regex (a.k.a. Regular Expressions) is a tool for finding words or patterns of text within strings. It is also used to validate text, for example to check that you have entered a valid email address. It’s a swiss army knife that you will use again and again in both web and back-end programming using Javascript.

Spread the love Related Posts How to Repeat Strings with JavaScriptThere are a few ways to repeat a string in JavaScript. JavaScript strings have a JavaScript Cheat Sheet — Operators and DatesJavaScript is one of the most popular programming languages for web programming. In this article, JavaScript Best Practices — Variables and StringsLike any kind of apps, JavaScript apps also. The tables below are a reference to basic regex. While reading the rest of the site, when in doubt, you can always come back and look here. (It you want a bookmark, here's a direct link to the regex reference tables).I encourage you to print the tables so you have a cheat sheet on your desk for quick reference. The JavaScript Cheat Sheet in a Nutshell. JavaScript is gaining much importance as a programming language. It is increasingly the go-to language for building web properties thanks to its proven track record and benefits. In the JavaScript cheat sheet above, we have compiled many of the most basic and important operators, functions, principles. The next column, 'Legend', explains what the element means (or encodes) in the regex syntax. The next two columns work hand in hand: the 'Example' column gives a valid regular expression that uses the element, and the 'Sample Match' column presents a text string that could be matched by the regular expression.

Before we look at the Javascript code, we’ll learn a bit about Regex itself.

Regex is a mini programming language in it’s own right, but for the purpose of finding text. With Regex you have a piece of text called an expression which is used to match text in a string. This text contains normal characters, e.g. letters that you want to match, and special characters that control how things are matched.

This is best explained with a few examples.

Javascript Regex Cheatsheet Pdf

Firstly let start with the simplest thing, let’s say the expression is just this:

The string we want to match on looks like this:

Then the expression will match the a in the word Mate.

In Javascript, you can use this regex to check if a string contains an a, and you can use it to replace any a’s with something else. I’ll cover the functions to do that later in this tutorial.

Now for something a bit more advanced

We are now going to use a special character, the asterisk *, which for a regex means match zero or more of a regular expression. This means if you have this regex:

It will match strings like this

These strings all have and a followed by zero or more b’s. When doing replacements, Javascript will replace as many b’s as it can find up until the next character that isn’t a b. For example. if you replace the regex ab* with x then abba becomes xa.

There are other special characters. The basic ones are:

  • Asterisk (*) as described above, matches zero, one or more of the preceding regex.
  • Plus sign (+) matches one or more of the preceding regex.
  • Question mark (?) makes the previous regex optional. So accepts zero or one match.
  • Backslash () used when you want to match a character that has been designated a special character. E.g. * matches a *
  • Period (.) used to match any character.

Let’s make an example of a simple email validator regex using just the above special characters. Our validation will assume that a valid email just needs an @ symbol somewhere inside it, and a period somewhere after the @.

E.g. this would be a valid email: justin@domain.com

This actually allow a lot of emails that would be invalid, but it gives you an idea of how to get started, and it can be modified to make it more precise. We’ll start with the obvious thing, the @ symbol, so you could have a regex like this:

We want to match anything before that symbol. To do this we will combine two special characters: the period and the plus:

The .+ means is match any character one or more times. Or in other words there needs to be something (anything) before the @ symbol.

In a similar way, let’s match anything after the @ symbol:

It feels like we are getting close. The only thing is we want that anything to contain a period, so we can add that:

Notice how we need to use the backslash to state that the period is just a period, not the special character.

The problem with this is it won’t match anything after that period, e.g. the com in .com, so now we need to add another match anything regex to the end:

And that’s it, that is our basic email matching regex

Let’s test it on a few strings:

It will match the first one but not the last two.

Javascript Regex Exercise

I have put the example above on a website that lets you experiment with regular expressions and what they match.

Javascript Regex Cheatsheet

Open the following link in a new tab: Regex Exercise on Regex101.com

You will see the regular expression for our email, and a test string with the 3 lines from above.Notice that on the right there is a single full match as you would expect:

Tasks:

  1. Add your own email to the test list. Once typed out it should appear in the matches section on the right.
  2. Add your name to the test list. Assuming there is no @ in your name, it should not appear on the right.
  3. Read the explanation section and make sure it matches your understanding of the regex. This section uses a bit of jargon:
    • Line terminators - these are characters that cause text to go on to the next line.
    • Greedy - this describes how + and * will consume as many characters as they can. For example. if you replace the regex ab* with x then abbbbbbbbbbbbba becomes ax. All the b’s are consumed.
  4. Change the regex to match only .com instead of matching anything after the period.
  5. Following on from 4, Add the email address justin@domain.co.uk and make sure that one doesn’t match, but the .com version does.

Learn more

The book

To learn about the regex syntax in depth, see Mastering Regular Expressions by Jeffrey E.F. Friedl

A quick cheat

If you are strapped for time, in a corner and need a quick regex to get you out, you might want to find a good cheatsheet online. Here is one I found which gets straight to the point: https://www.debuggex.com/cheatsheet/regex/javascript.

Javascript Regex

There has been a distinct lack of the usual braces and semicolons so far you’d expect from a Javascript tutorial. It’s time to fix that by seeing some regex code example. The regex language takes some time to get use to, but once you have a regex, using it in Javascript is easy.

Create a regex

To create a regex you can either put the regex text between two slashes, which is called a regular expression literal:

Or you can construct it like this:

The literal has the advantage of being pre-compiled, which can make it run faster. The constructed version should be used if you might need to change the pattern, or the pattern isn’t known at the time of writing the program (e.g. from an input field).

Once you have made your regex, there are 6 methods you can use with the regular expression to do useful things:

  • exec
  • test
  • match
  • search
  • replace
  • split

exec and test and methods on the regex object, and the rest are methods on the string you want to test or change.

Let’s go through these and see what they do.

exec

The exec method will search a string based on the regex, and will return some information about the first match if there is one, and will return null if there is no match.

Here is an example:

The information returned is an array whose first value is the first match, with some additional properties, which are:

  • The index of the match
  • The original string
  • Any group matches that were found. (We won’t cover group matches in this tutorial).

test

The test method is similar to exec but it returns less information. It will return true if there is a match and false if there isn’t, and that’s it.

match

The match method is called on a string. Given a regex it will return the match or matches found in the string. To find more than one match you need to add a g modifier to the regex.

For example:

search

The search method on a string returns the index (i.e. position) of the match within a string. It will return -1 if nothing is found. Either way, it will always return a number and not null/undefined.

replace

The replace method replaces the first match it finds with a substitution. You need to specify the global flag g after the regex if you want to replace all matches in the string.

You can also use normal strings instead of regex if you wish:

And if you are up for something a bit more advanced, you can provide a function that does the replacement in a special way. For example:

Extendclass.com has a good Regex Tester.

If you are looking for a JavaScript job or other tech job, I have created a free service called JobAlerts.

We grab jobs from around the world. Remote jobs, onsite jobs, all technologies from a tonne of trusted sources. Sign up to maximise your opportunities now!

See Also

Regular expressions, more commonly known as regex, is a powerful way of describing patterns in strings.

It can be pretty complicated, so I wrote this quick guide as a form of note-taking while learning about regex myself.

Usage in JavaScript

Characters

These special characters match specific character groups when used in a regular expression.

Regex Cheat Sheet Pdf

CharacterDescription
dA digit character (0 - 9)
wA word character (alphanumeric)
sA whitespace character (space, tab, newline, carriage return)
DA non-digit character
WA non-word character
SA non-whitespace character

As illustrated, the uppercase counterparts of each special character have opposite meanings to the lowercase characters.

An example use would be expressing one’s birth date in the format DD-MMM-YYYY:

Quantifiers

Repeating multiple special characters is pretty tedious. Thankfully, regex offers quantifiers as pattern suffixes to specify how many times a pattern should be matched.

QuantifierDescription
+One or more patterns
*Zero or more patterns
{2}Exactly twice
{2,5}Any number of times from 2 to 5, inclusive
{2,}2 or more times
?Zero or one pattern (meaning optional)

We can now simplify the regexp for a birth date as such:

Character Classes

Suppose we want to match any one of multiple patterns in a string. Character classes help with this.

ExpressionDescription
[0123456789]Any digit from 0 to 9
[0-9]Any digit from 0 to 9
[abcde]Any alphabet from a to e
[a-e]Any alphabet from a to e
[^0-9]Any character that isn’t 0 to 9
[^a-e]Any character that isn’t a to e