Regular expressions (also known as regex) are patterns used to match character combinations in strings. They are a powerful tool for text processing and are widely used for searching, validating, and manipulating text data.
RegExp object and various string methods.
What are Regular Expressions?
A regular expression is a sequence of characters that defines a search pattern. This pattern can be used to search, replace, or extract information from strings. Regular expressions are widely used for tasks like validation (e.g., email addresses, phone numbers) and text manipulation (e.g., removing whitespace or unwanted characters).
Here's a simple example of a regular expression that matches the word "cat" in a given string:
const regex = /cat/;
const text = 'I have a cat.';
const found = text.match(regex);
console.log(found); // ["cat"]
In this example, we define a regular expression by placing the pattern between two slashes
/pattern/. We then use the
match() method of the string object to search for the pattern within the string. If the pattern is found, it returns an array containing the matched string, otherwise, it returns
Simple String Matching
Regular expressions can be used to check if a string contains a specific pattern or not. In the following example, we'll use the
test() method provided by the
const regex = /dog/;
const text1 = 'I have a dog.';
const text2 = 'I have a cat.';
console.log(regex.test(text1)); // true
console.log(regex.test(text2)); // false
test() method returns
true if the pattern is found in the string, and