Tutorial Playlist
A lot of developers I know started out finding JavaScript regex incredibly complicated. The cryptic symbols and complex rules seemed overwhelming for beginners. However, with practice and a gradual approach, all the JS developers I know gained a solid understanding of regex's power in JavaScript.
All of my fellow JS developers can confidently use it for tasks like validation and text manipulation now. If you master JavaScript regex, you gain significant control and power over JS-based development.
Let us learn all the essential concepts related to regex in JS.
Regular expressions (or regex for short) are specialized sequences of characters that define a flexible search pattern within text. We can think of them as a sophisticated "find and replace" tool on steroids. Regex goes way beyond literal matching, it allows us to describe patterns based on character types, positions, repetitions, and more.
At their core, regular expressions are like a mini-language. This language uses a combination of normal characters (for literal matches) and special characters called metacharacters. These metacharacters (like ".", "*", "+") give us immense control in defining complex patterns. For instance, the regex \d{3}-\d{2}-\d{4} could describe an identitification number.
Regex is used in text manipulation for:
JavaScript offers two primary ways to work with regular expressions:
Here are the RegExp methods
Let us learn how to create these expressions with JavaScript regex examples. We will explore the two methods I mentioned earlier.
Syntax: Enclose your pattern between forward slashes, followed by optional flags: /pattern/flags
Pros: Simple and concise for patterns that don't change during execution.
Example: /hello/ would match the literal word "hello".
Syntax: new RegExp('pattern', 'flags')
Pros: Allows you to build patterns dynamically based on variables or user input. You pass the pattern and flags as strings.
Important note: When using the constructor, you need to escape backslashes twice (e.g., \\d to represent a digit).
Example:
let digits = "123"; let regex = new RegExp('\\d+' + digits, 'g'); // This would match "123" and other digit sequences. |
Let us now learn the basic JavaScript regex patterns.
The most straightforward elements such as regular letters, numbers, and some symbols match themselves, as we already covered in creating regular expressions.
There are the metacharacters:
These provide ways to match sets or ranges of characters:
Let us learn about quantifiers in JavaScript regex.
These quantifiers aim to match as much text as possible by default:
For finer control, use curly braces:
Lazy quantifiers match the shortest possible substring that satisfies the pattern. This is useful when you don't want to "overshoot" a match.
Add a ? after a greedy quantifier to make it lazy: (*?, +?, ??)
If you wish to learn javascript Regex online and all the other important JS concepts, you can enroll in the full stack development courses by upGrad.
Let us now learn about groups and backreferences in JavaScript regex.
Parentheses () create capturing groups, allowing you to "remember" parts of a regex match:
Groups without capturing, for when you want to group elements but don't need to reference them later.
Example:
The above regex has two capturing groups. \1 would reference "hello", \2 would reference "world"
These assert positions within the text, not matching characters:
Example:
/^\d{3}$/ matches exactly a 3-digit number at the beginning of the input.
Flags modify how regex matching behaves:
Let's explore some real-world use cases of regular expressions.
A basic email validation regex might look like this: /^[\w-.+]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
This pattern checks for an optional string of word characters, dots, hyphens, and plus signs before the '@', followed by a domain name and top-level domain. A more robust regex would be needed for full email standard compliance.
Here is a password strength validation regex:
/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()\-__+.]).{8,}$/
The above code looks complicated, but it uses lookaheads (we will cover this soon in the later section) to enforce:
Find all dates in a format: /(\d{2}\/\d{2}\/\d{4})/g
Capturing groups would let you extract month, day, year separately
Wrap HTML image names in <img> tags:
Search: (\w+\.(?:jpg|gif|png))
Replace: <img src="$1" alt="$1" />
Before we delve into some advanced JavaScript regex concepts, I would want to mention that lookarounds can make regex harder to read, so they should be used strategically. Also, overly complex regex can impact performance, so you should test with realistic data.
These allow you to assert what should be around a match without including it in the matched text. They use a special syntax:
Let's revisit our password regex using lookaheads,
Example: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()\-__+.]).{8,}$/
Each (?=.*pattern) asserts a condition must be true somewhere ahead but doesn't capture that part of the match.
The 'pipe' symbol (|) acts as an "OR" operator within a regex.
Example: /hello|goodbye|hola/ would match any of the words "hello", "goodbye", or "hola".
Combining complex patterns with other techniques opens up many possibilities such as validating variable or function names. A regex might combine alternation, lookarounds, and character classes to ensure specific naming rules are met.
Here is an example of JavaScript regex matches:
Code:
|
They are invaluable! Testers provide real-time feedback as you build and experiment with patterns. Here are some my favorite choices for JavaScript regex maker and tester experience:
Overly complex regexes can hurt performance, especially on large datasets. Here are some potential red flags:
When possible, consider alternative (non-regex) solutions for very complex tasks.
Regex is a valuable tool in any JavaScript development arsenal for working with text. The initial learning curve might be steep, but the rewards in terms of efficiency and flexibility are well worth the effort.
If you wish to master technologies such as JavaScript, you can enroll in upGrad’s software engineering courses.
Regex in JavaScript is used for pattern matching, searching, and manipulating text strings.
Regex offers concise and powerful pattern-matching in a single expression. It also saves development time for tasks that would otherwise require complex string manipulation code.
Any task involving string validation, searching, or text manipulation. We can also use it for form input fields, URL parsing, log analysis, etc.
You can create a RegExp object to represent the pattern:
let myRegex = /hello/;
Use the .test() method on the RegExp object:
myRegex.test("hello world"); // Returns true
Regex stands for "Regular Expression". It's a sequence of characters defining a specific search pattern.
mukesh
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .