Back to Blog Listing

Mastering Regular Expressions (Regex) in JS

Regular expressions (regex) are sequences of characters that define a search pattern. They are extremely useful for validating user inputs (like emails or passwords), extracting substrings, or replacing content inside text fields.

Creating a Regex in JavaScript

Regex can be defined using literal notation enclosed in slashes or by calling the RegExp constructor:

const pattern1 = /ab+c/i;
const pattern2 = new RegExp("ab+c", "i"); // "i" is flag for case-insensitivity

Common Methods

  • regex.test(str): Returns a boolean indicating if the pattern exists in the string.
  • str.match(regex): Returns an array of matches or null.
  • str.replace(regex, replacement): Replaces matches with a new string.
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailPattern.test("user@domain.com")); // true
💻

Try this code in our online compiler!

Don't just read about it. Write, run, and experiment with these JavaScript concepts instantly on our online workspace with autocomplete suggestions.

Share this tutorial:

CodeCompile