JavaScript Regular Expression Introduction (Live Playground)
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.
In JavaScript, regular expressions are supported by the 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 null
.
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 RegExp
object:
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
The test()
method returns true
if the pattern is found in the string, and false
otherwise.
Conclusion
In this introduction, we've learned what regular expressions are and how they can be used for simple string matching. In the next sections, we'll explore more advanced features and techniques for using regular expressions in JavaScript.