Code has been added to clipboard!

Learn JavaScript Regular Expression: RegEx JavaScript Explained

Reading time 4 min
Published Aug 8, 2017
Updated Oct 15, 2019

Regular expression, or simply RegEx JavaScript allows you to write specific search patterns. You can also make the search case-sensitive or insensitive, search for a single JavaScript RegEx match or multiple, look for characters at the beginning or the end of a word.

In this tutorial, you will learn how to work with RegEx JavaScript. It will cover the appropriate syntax, RegEx modifiers and patterns, which in turn are comprised of brackets, metacharacters, quantifiers. We will also explain what is a RegEx object and what methods are the most popular.

RegEx JavaScript: Main Tips

  • A regular expression is a string of text that makes a search pattern. It is formed using specific rules.
  • The text pattern can be used to make JavaScript RegEx replace and search text.
  • A regular expression can be a simple word or a complex pattern.
  • Using regular expressions instead of strings for search can be much more flexible. For example, you can look for a case-insensitive JavaScript RegEx match.
  • RegEx is a common abbreviation for regular expressions.

Syntax Standard

The example you can see below displays the syntax we use for JavaScript RegEx:

/pattern/modifiers;

Let's say we have /learn/i as our regular expression. learn is a search pattern. i is a modifier of the regular expression (it makes the search case-insensitive):

Example
var reg = /learn/i;

Using String Methods

Regular expressions are usually used with these two string methods: search() and replace(). We will now review both of them in more detail.

search() method searches for a specified pattern and returns the position of a JavaScript RegEx match (if finds any). The code in the JavaScript RegEx example below will find the position of the "Learn" string because the i modifier specifies the search to be case-insensitive:

Example
var text = "Learn computers";
var re = text.search(/learn/i);

search() method also accepts strings as arguments:

Example
var text = "Learn computer things today!";  
var str = text.search("computer");

Now, JavaScript RegEx replace() method replaces a specified pattern with a new string. In the JavaScript RegEx example below, the string "books" is replaced with a string "Movies":

Example
var text = "Books are the best.";
var re = text.replace(/books/i, "Movies");

Strings can also be accepted as arguments when using JavaScript RegEx replace():

Example
var text = "The best food is sushi.";  
var re = text.replace("sushi", "pizza");

Patterns and Modifiers

Whenever we need to find a range of characters, we use brackets. They can be round and square, depending on the situation:

Expression Description
[abc] True if any of the characters in brackets is found
[0-9] True if any of the numbers in brackets is found (can be specified in intervals)
(x|y) True if any of the alternatives separated by | symbol is found

Characters that have a special meaning are called metacharacters. Let's see them in a table to get a better idea:

Metacharacter Description
\d True if any number is found
\s True if a whitespace character is found
\b True if a JavaScript RegEx match is found at the end or beginning of a word
\uxxxx True if a character which is specified by a hexadecimal code is found

As the name itself tells us, quantifiers are used to define quantities:

Quantifier Description
n+ If a string contains at least one n, it's a match
n* If a string has zero or more of n, it's a match
n? If a string contains zero or one of n, it's a match

Now, modifiers are not patterns. However, they are very important to them, as they change the way a pattern is searched. Review the table to get a better idea how they affect the search:

Modifier Description
i Performs case-insensitive search
g Performs a global match (find all JavaScript RegEx matches rather than stopping after the first one)
m Performs multiline matching

Using RegEx Object

JavaScript language also has a RegEx object, which has its properties and methods. You can learn more about RegEx properties and objects in the JavaScript RegEx Reference tutorial. Now, however, we will discuss the most popular RegEx object methods.

First and foremost, the RegEx object has a test() method. It searches a defined string for a specified pattern and returns true if a JavaScript RegEx match is found.

The example below searches for an x character in a specified string:

Example
/a/.test("Things should always be learned from abc to xyz");

exec() is also a RegEx object method. Using it, the text you searched for is returned. The code is the example below is again used to look for an x character, but the return value is different:

Example
 /x/.exec("The letter a usually goes before the letter x");

RegEx JavaScript: Summary

  • A regular expression allows you to create search patterns with specific rules.
  • With RegEx JavaScript, you can either search for or replace a piece of text, by using string methods like search() and replace().
  • RegEx are made of modifiers and patterns. Patterns are comprised of brackets, metacharacters, and quantifiers.
What Is JavaScript Used For?
Tutorial
Introduction
Output
Syntax
Comment
Commands
Operators
Comparison and Logical Operators
Data Types
Math.random()
Type Conversion
Function Definitions
Events
Objects
Object Properties
Prototype
Array
Sorting Arrays
Strings
Numbers
Number Format
Math Object
Onclick Event
Date
Date Formats
Scope
Regular Expressions
Reserved Words
Common Mistakes
Performance
Forms
Form Validation
Window: The Browser Object Model
Popup Boxes
Cookies
JSON
AJAX Introduction
AJAX Form
Automatic File Download
Functions
Array Methods
String Methods
Date Methods
Timing Events
Cheat Sheet
JavaScript in HTML
HTML DOM Methods
HTML DOM Changing HTML
HTML DOM Animation
HTML DOM EventListener
HTML DOM Navigation
HTML DOM NodeList
HTML DOM Element Nodes
Array Functions
Boolean
Calling a Function
Date Functions
Global Objects
Input Text
Operator
Statements
String Functions
Math
Math.random
Number
RegEx
alert
array.filter
array.length
array.map
array.reduce
array.push
array.sort
break and continue
className
confirm
decodeURIComponent
for
forEach
if
indexOf
innerHTML
location.reload
number.toString
onclick
onload
parseInt
prompt
replace
setAttribute
setInterval
setTimeout
slice
splice
string.includes
string.indexOf
string.split
style.display
submit
substr
substring
switch
test
throw, try and catch
toLowerCase
toUpperCase
use strict
while
window.history
window.location
window.navigator
window.screen