Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Bootstrap Cheat Sheet - A Basic Guide to Bootstrap
Next article icon

JavaScript RegExp (Regular Expression)

Last Updated : 03 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A regular expression is a special sequence of characters that defines a search pattern, typically used for pattern matching within text. It’s often used for tasks such as validating email addresses, phone numbers, or checking if a string contains certain patterns (like dates, specific words, etc.).

In JavaScript, RegExp is an object that is used to create regular expressions, which are patterns used to match character combinations in strings.

JavaScript
// The /i flag makes the pattern case-insensitive const patt = /Geeks/i;  const s1 = "geeksforgeeks"; const s2 = "forgeeks";  console.log(patt.test(s1)); console.log(patt.test(s2)); 

Output
true true 

Creating a RegExp in JavaScript

There are two primary ways to create a RegExp in JavaScript

1. Using the RegExp Constructor

The RegExp constructor is useful when you need to create a regular expression dynamically, such as when the pattern or flags might change based on user input or other conditions.

JavaScript
let pattern = "hello";  // Pattern to match let flags = "i";  // Case-insensitive flag let regex = new RegExp(pattern, flags);  let s = "Hello world";  console.log(regex.test(s)); 

Output
true 
  • Here, we dynamically create a RegExp object using the RegExp() constructor.
  • The pattern “hello” will match the string “Hello” because of the ‘i’ flag, which makes the search case-insensitive.
  • regex.test(s) returns true because “Hello” matches the pattern “hello” in a case-insensitive manner.

2. Using Regular Expression Literal

This is the most common and simple way to create a regular expression in JavaScript. It’s especially useful when the pattern is static (doesn’t change dynamically).

JavaScript
let regex = /hello/i;  let s = "Hello world";  console.log(regex.test(s)); 

Output
true 
  • In this example, we define the regular expression directly using literal notation.
  • /hello/i means we’re looking for the word “hello”, and the ‘i’ flag ensures the search is case-insensitive.
  • regex.test(s) returns true because “Hello” matches the pattern “hello” case-insensitively.

Regular Expression Modifiers can be used to perform multiline searches which can also be set to case-insensitive matching: 

ExpressionsDescriptions
gFind the character globally
iFind a character with case-insensitive matching
mFind multiline matching

Regular Expression Brackets can Find characters in a specified range

ExpressionsDescription
[abc]Find any of the characters inside the brackets
[^abc]Find any character, not inside the brackets
[0-9]Find any of the digits between the brackets 0 to 9
[^0-9]Find any digit not in between the brackets
(x | y)Find any of the alternatives between x or y separated with |

Regular Expression Metacharacters are characters with a special meaning:

MetacharacterDescription
\.Search single characters, except line terminator or newline.
\wFind the word character i.e. characters from a to z, A to Z, 0 to 9
\dFind a digit
\DSearch non-digit characters i.e all the characters except digits
\sFind a whitespace character
\SFind the non-whitespace characters.
\bFind a match at the beginning or at the end of a word
\BFind a match that is not present at the beginning or end of a word.
\0Find the NULL character.
\nFind the newline character.
\fFind the form feed character
\rFind the carriage return character
\tFind the tab character
\vFind the vertical tab character
\uxxxxFind the Unicode character specified by the hexadecimal number xxxxx

Regular Expression Quantifiers are used to define quantitiesoccurrence

QuantifierDescription
n+Match any string that contains at least one n
n*Match any string that contains zero or more occurrences of n
n?Match any string that contains zero or one occurrence of n
m{X}Find the match of any string that contains a sequence of m, X times
m{X, Y}Find the match of any string that contains a sequence of m, X to Y times
m{X,}Find the match of any string that contains a sequence of m, at least X times
m$Find the match of any string which contains m at the end of it
^mFind the match of any string which contains m at the beginning of it
?!mFind the match of any string which is not followed by a specific string m.

Regular Expression Object Properties:

PropertyDescription
constructorReturn the function that created the RegExp object’s prototype
globalSpecify whether the “g” modifier is set or not
ignorecaseSpecify whether the “i” modifier is set or not
lastindexSpecify the index at which to start the next match
multilineSpecify whether the “m” modifier is set or not
sourceReturn the text of RegExp pattern

Regular Expression Object Methods:

MethodDescription
compile()Used to compile the regular expression while executing of script
exec()Used to test for the match in a string.
test()Used to test for a match in a string
toString()Return the string value of the regular expression

Use Cases of Regular Expressions

1. Validating Email Addresses

Regular expressions are frequently used for validating emails. Here’s an example that matches most email formats

JavaScript
let regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; console.log(regex.test("[email protected]")); 

Output
true 

2. Extracting Specific Data from a String

You can use regular expressions to extract specific data from a string, like extracting all numbers from a text.

JavaScript
let regex = /\d+/g; let res = "There are 123 apples and 456 oranges".match(regex); console.log(res); 

Output
[ '123', '456' ] 

3. Replacing Substrings

Regular expressions are often used in replacing certain substrings in text.

JavaScript
let regex = /foo/g; let res = "foo bar foo".replace(regex, "baz"); console.log(res); 

Output
baz bar baz 


Next Article
Bootstrap Cheat Sheet - A Basic Guide to Bootstrap

K

kundankumarjha
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-RegExp
  • javascript-string

Similar Reads

  • Markdown Cheat Sheet
    Markdown is a simple way to write and format text using plain text symbols. It's a lightweight language that lets you create nicely formatted text without the use of complex coding. The idea is to make it easy for people to read and understand the formatting, even if they're looking at the raw text.
    6 min read
  • CSS Cheat Sheet - A Basic Guide to CSS
    What is CSS? CSS i.e. Cascading Style Sheets is a stylesheet language used to describe the presentation of a document written in a markup language such as HTML, XML, etc. CSS enhances the look and feel of the webpage by describing how elements should be rendered on screen or in other media. What is
    13 min read
  • JavaScript Cheat Sheet - A Basic Guide to JavaScript
    JavaScript is a lightweight, open, and cross-platform programming language. It is omnipresent in modern development and is used by programmers across the world to create dynamic and interactive web content like applications and browsers JavaScript (JS) is a versatile, high-level programming language
    15+ min read
  • Git Cheat Sheet
    Git Cheat Sheet is a comprehensive quick guide for learning Git concepts, from very basic to advanced levels. By this Git Cheat Sheet, our aim is to provide a handy reference tool for both beginners and experienced developers/DevOps engineers. This Git Cheat Sheet not only makes it easier for newcom
    10 min read
  • React Cheat Sheet
    React is an open-source JavaScript library used to create user interfaces in a declarative and efficient way. It is a component-based front-end library responsible only for the view layer of a Model View Controller (MVC) architecture. React is used to create modular user interfaces and promotes the
    10 min read
  • JavaScript RegExp (Regular Expression)
    A regular expression is a special sequence of characters that defines a search pattern, typically used for pattern matching within text. It's often used for tasks such as validating email addresses, phone numbers, or checking if a string contains certain patterns (like dates, specific words, etc.).
    4 min read
  • Bootstrap Cheat Sheet - A Basic Guide to Bootstrap
    Bootstrap is a free, open-source, potent CSS framework and toolkit used to create modern and responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites. Nowadays, websites are perfect for all browsers and all
    15+ min read
  • jQuery Cheat Sheet – A Basic Guide to jQuery
    What is jQuery?jQuery is an open-source, feature-rich JavaScript library, designed to simplify the HTML document traversal and manipulation, event handling, animation, and Ajax with an easy-to-use API that supports the multiple browsers. It makes the easy interaction between the HTML & CSS docum
    15+ min read
  • Angular Cheat Sheet - A Basic Guide to Angular
    Angular is a client-side TypeScript-based, front-end web framework developed by the Angular Team at Google, that is mainly used to develop scalable single-page web applications(SPAs) for mobile & desktop. Angular is a great, reusable UI (User Interface) library for developers that helps in build
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences