Learn Regular Expressions in JavaScript

Regular expression is a programming tool widely used in many different programming languages to describe patterns in a string. It has a very cryptic syntax, but is also extremely useful.

Creating a regular expression

JavaScript offers two ways to create a regular expression. You can either use the RegExp() constructor:

javascript
1let regex = new RegExp("xyz");

Or a pair of forward slashes:

javascript
1let regex = /xyz/;

In this example, the regular expression matches the pattern "x followed by a y and then a z"

String matching

There is a built-in method for strings in JavaScript called match(), which allows you to match a string against a regular expression. For instance:

javascript
1let regex = /xyz/;
2let str = "This string contains the pattern xyz";
3
4console.log(str.match(regex));

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉