Regular Asdf
Regular Asdf
Regular expressions are patterns that allow you to describe, match, or parse text. With regular
expressions, you can do things like find and replace text, verify that input data follows the format
required, and and other similar things.
Here's a scenario: you want to verify that the telephone number entered by a user on a form matches a
format, say, ###-###-#### (where # represents a number). One way to solve this could be:
Alternatively, we can use a regular expression here like this:
function isPattern(userInput) {
return /^\d{3}-\d{3}-\d{4}$/.test(userInput);
}
Notice how we’ve refactored the code using regex. Amazing right? That is the power of regular
expressions.
How to Create A Regular Expression
In JavaScript, you can create a regular expression in either of two ways:
Method #1: using a regular expression literal. This consists of a pattern enclosed in forward
slashes. You can write this with or without a flag (we will see what flag means shortly). The
syntax is as follows:
const regExpLiteral = /pattern/; // Without flags
console.log(regExpStr.match(regExpLiteral));
// Output: ['Hello', 'hello']
Note that if we did not flag the pattern with i, only Hello will be returned.
The pattern /Hello/ is an example of a simple pattern. A simple pattern consists of characters that must
appear literally in the target text. For a match to occur, the target text must follow the same sequence
as the pattern.
For example, if you re-write the text in the previous example and try to match it:
const regExpLiteral = /Hello/gi;