JS RegExp Basics

JavaScript Regular Expressions (RegExp): A Beginner's Guide

A Regular Expression (often abbreviated as RegExp or Regex) is a sequence of characters that forms a search pattern.

When you search for data in a text, you can use this search pattern to describe exactly what you are looking for. Regular expressions are incredibly powerful for searching, replacing, and validating text (like checking if an email address is valid).


1. RegExp Syntax

A regular expression can be written simply as a pattern enclosed between two forward slashes /.

/pattern/modifiers;

Example:

/intricate/i is a regular expression.


2. Creating a Regular Expression

There are two ways to create a RegExp object in JavaScript:

Method 1: Literal Syntax (Recommended)

The literal syntax uses forward slashes /. This is evaluated when the script loads and provides better performance.

const regex1 = /hello/i;

Method 2: Constructor Function

You can also use the new RegExp() constructor. This is useful if your pattern is dynamic (e.g., coming from user input or a variable).

const regex2 = new RegExp("hello", "i");

3. Basic String Methods with RegExp

In JavaScript, regular expressions are most commonly used with the built-in String methods search() and replace().

Using String search() with a String vs RegExp

The search() method searches a string for a specified value and returns the position of the match.

search() with RegExp Example

let text = "Welcome to IntricateDevo!";

// Search using a normal string let n1 = text.search("intricatedevo"); // Returns -1 (case-sensitive, no match)

// Search using a RegExp with the 'i' (case-insensitive) flag let n2 = text.search(/intricatedevo/i); // Returns 11

console.log("String search:", n1); console.log("RegExp search:", n2);

Using String replace() with a String vs RegExp

The replace() method replaces a specified value with another value in a string. Using a regular expression allows you to replace values regardless of case!

replace() with RegExp Example

let text = "Please visit Microsoft!";

// This replaces "microsoft" (case-insensitive) with "IntricateDevo" let newText = text.replace(/microsoft/i, "IntricateDevo");

console.log(newText);


Exercise

?

Which of the following is the correct literal syntax to create a regular expression that searches for "apple" in a case-insensitive manner?