Regular Expressions in JavaScript

JK1820 
Created at Feb 12, 2024 12:18:02
Updated at Oct 03, 2024 05:00:24 
  6,705   0   0  

Regular expressions in JavaScript are a powerful tool for working with strings. They allow you to search for patterns within strings and manipulate them as needed. Here's a basic overview:

Creating Regular Expressions: You can create a regular expression in JavaScript by enclosing the pattern in forward slashes (/). For example:

var regex = /pattern/;

Using Constructors: You can also create a regular expression using the RegExp constructor, which takes a string argument:

var regex = new RegExp("pattern");

Searching: Regular expressions are commonly used with methods like match(), search(), and replace() to search for patterns within strings and manipulate them.

var str = "Hello World";
var regex = /World/;

console.log(str.match(regex)); // Outputs: ["World"]
console.log(str.search(regex)); // Outputs: 6 (index of the match)

var replacedStr = str.replace(regex, "Universe");
console.log(replacedStr); // Outputs: "Hello Universe"

Modifiers: Regular expressions can have modifiers like i (case-insensitive), g (global search), and m (multiline). These can be added after the closing slash of the regular expression.

var regex = /pattern/i; // case-insensitive search
var regexGlobal = /pattern/g; // global search

Pattern Matching: Regular expressions can match various patterns, including literal characters, character classes, quantifiers, anchors, and more.

  • . matches any single character except newline characters.
  • \d matches any digit.
  • \w matches any word character (alphanumeric plus underscore).
  • \s matches any whitespace character.
  • ^ matches the beginning of the string.
  • $ matches the end of the string.
var regex = /\d+/; // matches one or more digits
var regexWord = /\w+/; // matches one or more word characters

Escaping Special Characters: If you want to match special characters like ., $, *, etc., you need to escape them with a backslash (\), as they have special meanings in regular expressions.

var regex = /\$/; // matches the dollar sign

Regular expressions can get quite complex, but they are extremely powerful for string manipulation and searching. However, they can also be a bit tricky to understand at first. Practice and experimentation are key to mastering them.


Associated Data:

  • Common uses of regular expressions in JavaScript:
    • Validating user input (email addresses, phone numbers, passwords)
    • Parsing text data (extracting specific information from strings)
    • Searching and replacing text
    • Code analysis (finding patterns in code)
    • URL manipulation
  • Popular libraries for working with regular expressions in JavaScript:
    • RegExp - Built-in JavaScript library for working with regular expressions.
    • XRegExp - Provides extended functionality and support for Unicode.
    • String.prototype.matchAll - A newer JavaScript method that allows for iterating over all matches of a regular expression in a string.
  • Resources for learning more about regular expressions in JavaScript:
  • Example use cases of specific regex patterns:
    • `/\d{3}-\d{3}-\d{4}/`: Matching a US phone number
    • `[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}`: Matching an email address
    • `^(?:(?:https?|ftp)://)?(?:[A-Z0-9][A-Z0-9\-]{0,61}[A-Z0-9]\.)+[A-Z]{2,6}\/?$`: Matching a URL
  • Debugging and testing regular expressions:
    • Using online regex testers like Regex101 (see above)
    • Using the `console.log` function in your JavaScript code to inspect the results of your regex operations.
  • Key concepts in regular expressions:
    • Character classes: Represent a set of characters (e.g., `[a-z]`, `\d`)
    • Quantifiers: Specify how many times a character or group should appear (e.g., `*`, `+`, `?`)
    • Anchors: Indicate specific positions in the string (e.g., `^`, `$`)
    • Grouping: Combine parts of the pattern into a single unit (e.g., `(...)`)
    • Lookarounds: Assert conditions without including them in the match (e.g., `(?=...)`, `(?!...)`)
  • Advanced regular expression concepts:
    • Backreferences: Referencing captured groups within the pattern
    • Recursion: Defining patterns that can be repeated
    • Unicode support: Matching characters from different alphabets


Tags: JavaScript RegExp Regular Expression Share on Facebook Share on X

▶ NEXT
Difference between Java and Javascript

  Comments 0
SIMILAR POSTS

How do I replace content that based on the HTML UI Template

(created at Feb 12, 2024)

Difference between Java and Javascript

(updated at Oct 03, 2024)

RegExp example in Python to exclude javascript from HTML code

(created at Mar 22, 2024)

Loading XML Data with JavaScript

(updated at Oct 03, 2024)

Block unwanted URLs for comfortable web browsing with Chrome Addon - URL Blocker

(updated at Nov 01, 2024)

OTHER POSTS IN THE SAME CATEGORY

Loading XML Data with JavaScript

(updated at Oct 03, 2024)

jQuery Example to make GET method call with $.ajax()

(updated at Oct 03, 2024)

Difference between Java and Javascript

(updated at Oct 03, 2024)

UPDATES

BABYMONSTER(베이비몬스터) - DRIP + HOT SOURCE + SHEESH

(created at Oct 08, 2025)

Common Naming Format in Software Development

(created at Oct 07, 2025)

In a life where I don't want to spill even a single sip of champagne - Chan-Hyuk Lee - Panorama(파노라마)

(created at Oct 06, 2025)

Countries with more males and females - what about UIUC?

(created at Oct 04, 2025)

Challenge: One Code Problem Per Day

(created at Oct 03, 2025)

Urban planning and growth from a historical perspective

(created at Sep 28, 2025)

Jackbryan VS Serpent | Korea Beatbox Championship 2023 | Quarterfinal

(created at Sep 28, 2025)

CNBLUE - You've Fallen For Me (넌 내게 반했어)

(created at Sep 28, 2025)

GGIS: The Roots of Visualizing Geographic Information

(created at Sep 27, 2025)

CNBLUE - 외톨이야 (aka Outsider)

(created at Sep 27, 2025)

Did you know that the person who voiced Humtrix Rumi in KPop Demon Hunters went to UIUC?

(updated at Sep 05, 2025)

WING - Dopamine

(created at Sep 05, 2025)

CARDIO VS Jackbryan | Korea Beatbox Championship 2025 | Semifinal

(updated at Sep 04, 2025)

Tech Visionaries who graduated at UIUC - You are the Next Turn

(updated at Sep 04, 2025)

Thinking about the Public Dataset and Open API provided for the Authorized People

(updated at Sep 04, 2025)

Where to Eat with Your i-Card at UIUC and How to Track Your Dining Dollars

(updated at Sep 04, 2025)

OMG! Did you consume your meals already at UIUC? How do you change the meal plan?

(updated at Sep 03, 2025)

Java Comments

(updated at Sep 03, 2025)

Abraham Lincoln Contributed to UIUC's Creation and its Mission

(created at Sep 03, 2025)

Feeling weak? Transform yourself at the UIUC ARC!

(updated at Sep 03, 2025)

Checking Your Upcoming Assignment/Exam Schedule: Using the UIUC Canvas Dashboard for Assignment Management

(updated at Sep 03, 2025)

UIUC Course Map for CS and Blended CS Degrees

(updated at Sep 02, 2025)

What You Need to Prepare for Graduate University at UIUC

(updated at Sep 01, 2025)

Did you know about the UIUC Course Numbering Policy? How to meet with 120 GPA hours?

(created at Sep 01, 2025)

My Dad's Bucket Hat Craze: One Man's Quest for Collegiate Headwear

(created at Aug 30, 2025)

Public Transportation between Chicago O'Hare International Airport and UIUC (University of Illinois at Urbana-Champaign)

(updated at Aug 27, 2025)

How to Receive Mail and Packages in University Housing at UIUC

(updated at Aug 27, 2025)

When you are too busy to have your breakfast/lunch/dinner, use Good2Go Carryout Program

(created at Aug 27, 2025)

Why Outlook’s Redirection Option Is a Game-Changer

(updated at Aug 27, 2025)

Why Every Freshman Needs the Illinois App at UIUC

(updated at Aug 24, 2025)

My First Day at University of Illinois-Urvana Champaign

(created at Aug 22, 2025)

Did you get Selective Service System(SSS) Form 3C?

(updated at Aug 17, 2025)

BlackPink's refreshing song - Jump

(updated at Aug 08, 2025)

Poisonous Mushrooms sprouted along the roadside after Typhoon

(updated at Aug 06, 2025)

Annual Weather Forecasting in Illinois based on Month

(updated at Aug 06, 2025)

My name has a typo in MyIllini - Need a Biographical change form

(updated at Jul 31, 2025)

Free Transportation Systems for UIUC students, faculty, and staff with I-Card

(updated at Jul 31, 2025)

What you can do with I-Card at UIUC

(updated at Jul 31, 2025)

Selecting a Bed Configuration before you move-in at UIUC Dormitory

(updated at Jul 30, 2025)

Student Health Insurance Waiver: Major Deadlines You Can’t Miss

(updated at Jul 22, 2025)

Types of Memory and Storage

(updated at Jul 22, 2025)

Sample Curriculum Comparison CS versus CS+GGIS at UIUC

(updated at May 31, 2025)

UIUC 2025-2026 Academic Calendar

(updated at May 26, 2025)

IU (아이유) appeared at Mask Singer with Violet Fragrance (보라빛 향기)

(updated at Apr 17, 2025)

What is Model Context Protocol (MCP)? How to build AI Agents?

(updated at Apr 17, 2025)

송소희(Song Sohee) - Not a Dream

(updated at Apr 08, 2025)

DOH KYUNG SOO & LEE SUHYUN - Rewrite The Stars cover

(created at Apr 08, 2025)

😲😭 디오(D.O.) - 후라이의 꿈 + Rewrite the stars(with. 수현)

(created at Apr 08, 2025)

D.O. (도경수) & IU (아이유) - Love Wins All | IU’s Palette (아이유의 팔레트)

(updated at Apr 08, 2025)

Lie - Legend song by BIGBANG

(updated at Feb 26, 2025)