Lesson 61 - Introduction to Regular Expressions in JavaScript
Regular Expressions (RegEx) are patterns used to match character combinations in strings. In JavaScript, RegEx is used with methods like test()
and match()
for searching and replacing text.
What is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern. It can be used to check if a string contains a specified pattern.
Creating a Regular Expression
There are two ways to create a RegEx in JavaScript:
-
Using literals (preferred when the pattern is constant):
let pattern = /hello/;
-
Using the RegExp constructor (useful for dynamic patterns):
let pattern = new RegExp("hello");
Using Regular Expressions
Regular expressions are commonly used with two methods:
-
test() - Returns
true
if the pattern is found, otherwisefalse
:let regex = /world/; console.log(regex.test("hello world")); // true console.log(regex.test("hello")); // false
-
match() - Returns an array of matches or
null
if no match is found:let text = "The rain in Spain stays mainly in the plain."; let result = text.match(/ain/g); console.log(result); // ["ain", "ain", "ain", "ain"]
Flags in Regular Expressions
Flags modify the behavior of a regular expression. Some common flags include:
g
(global) - Finds all matches instead of stopping at the first one.i
(case-insensitive) - Ignores case while matching.m
(multiline) - Enables multi-line matching.
Example:
let pattern = /hello/i; // Case-insensitive match
console.log(pattern.test("Hello")); // true
Try Your Hand
Write a JavaScript function that checks if a given string contains the word "JavaScript" (case-insensitive).
function containsJavaScript(text) {
let regex = /javascript/i;
return regex.test(text);
}
console.log(containsJavaScript("I love JavaScript!")); // true
console.log(containsJavaScript("I love coding.")); // false
Next, we will explore different pattern matching techniques using RegEx!