JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript RegExp


Regular expressions (RegExp) in JavaScript are patterns used to match, search, and manipulate strings. They are extremely powerful for validating input, parsing text, and performing replacements.

RegExp can be confusing at first, but once you understand the syntax and methods, it becomes a versatile tool for string operations.

JavaScript supports two ways to create regular expressions:

  • Using a literal notation: /pattern/flags

  • Using the RegExp constructor: new RegExp("pattern", "flags")

Creating Regular Expressions

// Literal notation
let regex1 = /hello/;

// Constructor notation
let regex2 = new RegExp("hello");

// Testing the regex
console.log(regex1.test("hello world")); // Logs: true
console.log(regex2.test("hi there"));   // Logs: false
  • Literal notation is faster and more readable.

  • Constructor notation is useful when the pattern is dynamic.

Flags

Flags modify how the pattern is applied:

  • g – Global search (find all matches)

  • i – Case-insensitive search

  • m – Multiline search

  • s – Allows dot . to match newline characters

  • u – Unicode mode

  • y – Sticky search (matches from lastIndex only)

let text = "Hello hello";
let regex = /hello/gi; // Case-insensitive and global
console.log(text.match(regex)); // Logs: ["Hello", "hello"]

Basic Patterns

Character Matching

let regex = /a/; // Matches the character 'a'
console.log(regex.test("apple")); // true
console.log(regex.test("banana")); // true
console.log(regex.test("cherry")); // false

Metacharacters

  • . – Matches any single character except newline

  • \d – Matches any digit [0-9]

  • \D – Matches any non-digit

  • \w – Matches any word character [a-zA-Z0-9_]

  • \W – Matches any non-word character

  • \s – Matches any whitespace character

  • \S – Matches any non-whitespace character

let regex = /\d/; 
console.log(regex.test("abc123")); // true

Quantifiers

Quantifiers define how many times a character or group can occur:

  • * – Zero or more times

  • + – One or more times

  • ? – Zero or one time

  • {n} – Exactly n times

  • {n,} – At least n times

  • {n,m} – Between n and m times

let regex = /\d{2,4}/; // Match 2 to 4 digits
console.log("12345".match(regex)); // Logs: ["1234"]

Character Sets and Ranges

Character sets [ ] allow matching any character inside:

let regex = /[aeiou]/g; // Match vowels
console.log("hello world".match(regex)); // Logs: ["e","o","o"]
  • Ranges [a-z] match characters in a specific range.

Anchors

Anchors match positions in the string:

  • ^ – Start of string

  • $ – End of string

let regex = /^Hello/;
console.log(regex.test("Hello world")); // true
console.log(regex.test("world Hello")); // false
  • Useful for validating input formats.

Grouping and Capturing

Parentheses ( ) are used to group expressions and capture matches:

let regex = /(ab)+/; // Matches one or more repetitions of "ab"
console.log("ababab".match(regex)); // Logs: ["ababab"]
  • Captured groups can be accessed using match or RegExp.$1, $2, etc.

Special Sequences

  • \b – Word boundary

  • \B – Non-word boundary

  • (?=...) – Positive lookahead

  • (?!...) – Negative lookahead

let regex = /\d(?=px)/; // Match digits only if followed by "px"
console.log("10px 20em".match(regex)); // Logs: ["1"]
  • Lookahead is useful for conditional matching without including it in the result.

RegExp Methods

test()

Returns true if the pattern matches the string:

let regex = /hello/i;
console.log(regex.test("Hello World")); // true

exec()

Returns an array containing the first match and captured groups:

let regex = /(\d+)/;
let result = regex.exec("I have 42 apples");
console.log(result); // Logs: ["42", "42"]

String Methods

  • match() – Returns all matches

  • replace() – Replaces matched parts

  • search() – Returns the index of the match

  • split() – Splits string using regex

let text = "apple, banana, cherry";
console.log(text.split(/, /)); // ["apple", "banana", "cherry"]

let replaced = text.replace(/banana/, "orange");
console.log(replaced); // "apple, orange, cherry"

Practical Example: Email Validation

function validateEmail(email) {
  let regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/;
  return regex.test(email);
}

console.log(validateEmail("test@example.com")); // true
console.log(validateEmail("invalid-email"));    // false
  • The regex checks for a basic email format, ensuring a valid username, @ symbol, domain, and extension.

Summary of the Tutorial

  • Regular expressions allow pattern matching and manipulation of strings.

  • Use literal or constructor notation to define regex.

  • Flags control global search, case sensitivity, multiline, etc.

  • Patterns include characters, metacharacters, quantifiers, anchors, groups, and lookaheads.

  • Methods like test(), exec(), match(), replace(), search(), and split() are essential for working with RegExp.

  • RegExp is widely used for validation, parsing, text replacement, and data extraction.

Mastering JavaScript RegExp is crucial for efficient text processing and complex string manipulations in modern web development.


Practice Questions

  1. Write a regular expression to test if a string contains the word "JavaScript" (case-insensitive).

  2. Use a regular expression to extract all digits from the string "I have 2025 apples and 30 oranges".

  3. Create a regex that matches a valid email address and test it on "test@example.com" and "invalid-email".

  4. Use a regular expression to replace all spaces in the string "Hello World From JS" with hyphens (-).

  5. Write a regex to match all words that start with the letter b in the string "banana band ball bat" and return them as an array.

  6. Create a regex to validate a US phone number format like "123-456-7890" and test it on a valid and invalid number.

  7. Use regex to check if a string starts with "Hello" and ends with "JS" in "Hello from JavaScript JS".

  8. Write a regex to split the string "apple,banana;cherry|date" by commas, semicolons, or pipes.

  9. Create a regex to match all HTML tags in the string "<div>Hello</div><p>World</p>" and log the results.

  10. Use regex with lookahead to find digits in "50px, 20em, 100%" that are followed by "px" only.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top