A JavaScript Regular Expression (or Regex) is a sequence of characters that we can utilize to work effectively with strings. Using this syntax, we can:
- search for text in a string
- replace substrings in a string
- extract information from a string
Dating back to the 1950s, Regular Expressions were formalized as a concept for pattern searching in string-processing algorithms.
JavaScript has regular expressions support directly built into the language. A solid understanding of regular expressions will make you a much more effective programmer. So letâs get started!
A very basic Regex pattern
Hereâs a basic pattern:
var regex = /hello/;
console.log(regex.test('hello world'));
// true
We are simply matching the literal text with the test string. Weâll look at the regex test method in detail shortly...
Why use Regular Expressions?
As mentioned, Regular Expressions are a way to describe patterns in string data. We can use them to check a string of characters, for example, to look for an e-mail address â by matching the pattern which is defined by our regular expression.
Creating a Regular Expression
In JavaScript, we can create a Regular Expression in two ways: Either by using the RegExp constructor or by using forward slashes /
 to enclose the regex pattern.
The constructor method:
The syntax is like so:
new RegExp(pattern[, flags])
So for example:
let regexConst = new RegExp('abc');
The literal method:
The syntax is like so:
/pattern/flags
An example:
let regexLiteral = /abc/;
Note:Â flags are optional, weâll look at these later in this article!
In the case where you need to create regular expressions dynamically, youâll need to use the constructor method.
In either case, the result will give a regex object â which will have the same methods and properties attached to them, for our use.
Regular Expression Methods
When testing our regular expressions, we generally use one of two methods:Â RegExp.prototype.test()
 or RegExp.prototype.exec()
.
RegExp.prototype.test()
We use this method to test whether a match has been found or not. It accepts a string which we test against a regular expression and returns either true
or false
, depending if the match is found or not.
Letâs see an example:
let regex = /hello/;
let str = 'hello world';
let result = regex.test(str);
console.log(result);
// returns 'true' as hello is present in our string
RegExp.prototype.exec()
We use this method to receive an array of all the matched groups. It accepts a string that we test against our regular expression.
An example:
let regex = /hello/;
let str = 'hello world';
let result = regex.exec(str);
console.log(result);
// returns [ 'hello', index: 0, input: 'hello world', groups: undefined ]
In this example, âhelloâ
 is our matched pattern, index
 is where the regular expression starts & input
 is the string that was passed.
For the rest of the article, weâll be using the test()
 method.
The Power of Regex
Weâve so far seen how to create simple regular expression patterns. This is really just the tip of the iceberg. Letâs now take a dive into the syntax to see the full power of regular expressions for handling more complex tasks!
An example of a more complex task would be if we needed to match a number of email addresses. By using the special characters defined in the syntax â we can achieve this!
Letâs take a look now so we can more fully grasp & therefore utilize regular expressions in our programs.
Flags:
In any regular expression, we can use the following flags:
g
: matches the pattern multiple timesi
: makes the regex case insensitivem
: enables multi-line mode. WhereÂ^
 andÂ$
 match the start and end of the entire string. Without this, multi-line strings match the beginning and end of each line.u
: enables support for unicodes
: short for single line, it causes theÂ.
 to also match new line characters
Flags may also be combined in a single regular expression & the flag order doesnât matter. They are added at the end of the string in regex literals:
/hello/ig.test('HEllo')
// returns true
If using RegExp object constructors, theyâre added as the second parameter:
new RegExp('hello', 'ig').test('HEllo')
// returns true
Character groups:
Character set [abc]
We use character sets to match different characters in a single position. They match any single character in the string with the characters inside the brackets:
let regex = /[hc]ello/;
console.log(regex.test('hello'));
// returns true
console.log(regex.test('cello'));
// returns true
console.log(regex.test('jello'));
// returns false
Negated character set [^abc]
It matches anything that is not enclosed in the brackets:
let regex = /[^hc]ello/;
console.log(regex.test('hello'));
// returns false
console.log(regex.test('cello'));
// returns false
console.log(regex.test('jello'));
// returns true
Ranges [a-z]
If we want to match all of the letters of an alphabet in a single position, we can use ranges. For example: [a-j] will match all the letters from a to j. We can also use digits like [0â9] or capital letters like [A-Z]:
let regex = /[a-z]ello/;
console.log(regex.test('hello'));
// returns true
console.log(regex.test('cello'));
// returns true
console.log(regex.test('jello'));
// returns true
If at least one character exists in the range we test, itâll return true:
/[a-z]/.test('a') // true
/[a-z]/.test('1') // false
/[a-z]/.test('A') // false (as our range is in lower case)
/[a-c]/.test('d') // false
/[a-c]/.test('cd') // true (as 'c' is in the range)
Ranges can also be combined using -
:
/[A-Z-0-9]/
/[A-Z-0-9]/.test('a') // false
/[A-Z-0-9]/.test('1') // true
/[A-Z-0-9]/.test('A') // true
Multiple range item matches
We can check if a string contains one or only one character in a range. Start the regex with ^
 and end with$
 :
/^[A-Z]$/.test('A') // true
/^[A-Z]$/.test('AB') // false
/^[A-Z]$/.test('Ab') // false
/^[A-Z-0-9]$/.test('1') // true
/^[A-Z-0-9]$/.test('A1') // false
Meta-characters
Meta-characters are characters with a special meaning. Letâs take a look at some of these here:
\d
 : matches any digit, being[0-9]
\D
: matches any character that is not a digit, effectively[^0-9]
\w
: matches any alphanumeric character (plus underscore), equivalent toÂ[A-Za-z_0-9]
\W
: matches any non-alphanumeric character, so anything exceptÂ[^A-Za-z_0-9]
\s
: matches any whitespace character: spaces, tabs, newlines and Unicode spaces\S
: matches any character that is not a whitespace\0
: matches null\n
: matches a newline character\t
: matches a tab character\uXXXX
: matches a unicode character with code XXXX (requires theÂu
 flag).
: matches any character that is not a newline char (e.g.Â\n
) (unless you use theÂs
 flag, explained later on)[^]
: matches any character, including newline characters. Itâs very useful on multi-line strings
Quantifiers
Quantifiers are symbols that have unique meaning in regex.
Letâs see them in action:
+
Matches the preceding expression 1 or more times:
let regex = /\d+/;
console.log(regex.test('1'));
// true
console.log(regex.test('1122'));
// true
*
Matches the preceding expression 0 or more times:
let regex = /\d+/;
console.log(regex.test('1'));
// true
console.log(regex.test('1122'));
// true
?
Matches the preceding expression 0 or 1 time, that is preceding pattern is optional:
let regex = /hii?d/;
console.log(regex.test('hid'));
// true
console.log(regex.test('hiid'));
// true
console.log(regex.test('hiiid'));
// false
^
Matches the beginning of the string, the regex that follows should be at the start of the test string:
let regex = /^h/;
console.log(regex.test('hi'));
// true
console.log(regex.test('bye'));
// false
$
 Matches the end of the string, the regex that precedes it should be at the end of the test string:
let regex = /.com$/;
console.log(regex.test('test@email.com'));
// true
console.log(regex.test('test@email'));
// false
{N}
 Matches exactly N occurrences of the preceding regex:
let regex = /hi{2}d/;
console.log(regex.test('hiid'));
// true
console.log(regex.test('hid'));
// false
{N,}
 Matches at least N occurrences of the preceding regular expression.
let regex = /hi{2,}d/;
console.log(regex.test('hiid'));
// true
console.log(regex.test('hiiid'));
// true
console.log(regex.test('hiiiid'));
// true
{N,M}
 Matches at least N occurrences and at most M occurrences of the preceding regex (when M > N).
let regex = /hi{1,2}d/;
console.log(regex.test('hid'));
// true
console.log(regex.test('hiid'));
// true
console.log(regex.test('hiiid'));
// false
X|Y
 Alternation matches either X or Y:
let regex = /(red|yellow) bike/;
console.log(regex.test('red bike'));
// true
console.log(regex.test('yellow bike'));
// true
console.log(regex.test('brown bike'));
// false
Note: To use any special character as a part of the expression, for example if you want to match literal +
 or .
, then youâll need to escape them with a backslash \
. Like so:
let regex = /a+b/;
// this doesn't work
var regex = /a\+b/;
// this works!
console.log(regex.test('a+b'));
// true
Reviewing Regex
With these concepts fresh in our minds, letâs review what weâve learned!
Match any 10 digit number:
let regex = /^\d{10}$/;
console.log(regex.test('4658264822'));
// true
So \d
 matches any digit character. {10}
 matches the previous expression, in this case \d
 exactly 10 times. So if the test string contains less than or more than 10 digits, the result will be false.
Match a date with the following format:
DD-MM-YYYY
or DD-MM-YY
let regex = /^(\d{1,2}-){2}\d{2}(\d{2})?$/;
console.log(regex.test('01-01-2000'));
// true
console.log(regex.test('01-01-00'));
// true
console.log(regex.test('01-01-200'));
// false
Here weâve wrapped the entire expression inside ^
and $
, so that the match spans the entire string. (
 is the start of first sub-expression. \d{1,2}
 matches at least 1 digit and at most 2 digits. -
 matches the literal hyphen character. )
 is the end of first sub-expression.
Then {2}
 matches the first sub-expression exactly 2 times. \d{2}
 matches exactly 2 digits. (\d{2})?
 matches exactly 2 digits. However itâs optional, so either year contains 2 digits or 4 digits.
Conclusion
And there we go! Weâve examined Regular Expressions from the very basics right through to more advanced implementations. Including both the literal and constructor methods, testing methods, flags and character syntax.
Regular expressions can indeed be fairly complex! However, taking the time to learn the syntax will greatly help you to identify the regex patterns more easily. Any new confidence you gain will surely have you ready to conquer the next obstacle you encounter on your coding journey!
A little about me..
Hey, Iâm Tim! đ
Iâm a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out my Complete Guide to Freelancing if you'd like to find out more.
While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.
Thanks for reading! đ