In this tutorial, you’ll learn about the JavaScript regular expressions. After the tutorial, you’ll know how to use regular expressions effectively to search and replace strings.
A regular expression is a string that describes a pattern e.g., email addresses and phone numbers.
In JavaScript, regular expressions are objects. JavaScript provides the built-in RegExp
type that allows you to work with regular expressions effectively.
Regular expressions are useful for searching and replacing strings that match a pattern. They have many useful applications.
For example, you can use regular expressions to extract useful information in web scraping like product prices. Or you can use regular expressions to validate form fields like email addresses and phone numbers.
To create a regular expression in JavaScript, you enclose its pattern in forward-slash (/
) characters like this:
let re = /hi/;
Note that a regular expression doesn’t have single quotes or double quotes like a regular string.
Or you can use the RegExp
constructor:
let re = new RegExp('hi');
Both regular expressions are the instances of the RegExp
type. They match the string 'hi'
.
The RegExp
object has many useful methods. One of them is the test()
method that allows you to test if a string contains a match of the pattern in the regular expression.
The test()
method returns true
if the string argument contains a match.
The following example shows how to use the test()
method:
let re = /hi/;
let result = re.test('hi John');
console.log(result); // true
#javascript #programming #developer #web-service