JS Regular Expression

Understanding JavaScript Regular Expressions (RegEx)

What Are Regular Expressions?

In JavaScript, RegEx is a way to search and match patterns in strings (a string is a sequence of characters). They help you find text, replace parts of text, or check if certain patterns exist in a string.

Imagine you have a huge book filled with text. Now, let’s say you want to find all the words that start with the letter “a”. Instead of manually searching through every page, you could use a special tool to do it for you automatically. Regular expressions (RegEx) are like these special search tools!

Why Do We Use Regular Expressions?

Regular expressions can be incredibly powerful for solving problems like:

   Finding specific words or patterns in a big chunk of text (e.g., emails, phone numbers).
   Checking if something is correct (like whether a user has entered a valid email address).
   Replacing parts of text with something else (for example, changing all instances of “dog” to “cat”).

How Do Regular Expressions Work?

At the heart of a regular expression is a pattern. This pattern is like a blueprint that tells JavaScript exactly what you’re looking for in a string.

Syntax:

A regular expression is defined using the following syntax:

const regex = /pattern/;

Const-Pattern
Let's look at a basic example:

let pattern = /hello/;

This pattern will look for the word “hello” in any string.

Breaking Down the Basics of Regular Expressions

1. The Delimiters: / and /

In JavaScript, regular expressions are written between two slashes (/). These slashes are like bookends that keep your pattern safe and tell JavaScript where your pattern starts and ends.

2. Simple Matching

If you just want to find an exact word, you write it directly inside the slashes. For example:

let pattern = /apple/;

This pattern will search for the word “apple.” If the string contains “apple,” it will match. If it doesn’t, there will be no match.

Example Code:

let text = “I love apple pie!”;
let pattern = /apple/;
console.log(pattern.test(text)); // Output: true (because ‘apple’ exists in the string)

3. Special Characters

Regular expressions use special symbols to make patterns more powerful and flexible. Let’s look at a few of them:

•  . (Dot): Matches any character except newlines.

let pattern = /a.b/;
console.log(pattern.test(“acb”)); // Output: true (because ‘a’ and ‘b’ have any character between them)

What happens when we use two dots in a pattern.?

let pattern = /a..b/;
console.log(pattern.test(“acb”));// Output: false (because ‘a’ and ‘b’ doesn’t have two character between them)

  ^ (Caret): Matches the beginning of a string.

let pattern = /^hello/;
console.log(pattern.test(“hello world”)); // Output: true (because ‘hello’ is at the start)

What happens when we use hello at the end.?

let pattern = /^hello/;
console.log(pattern.test(“world hello”));// Output: false (because ‘hello’ is not at the start)

•  $ (Dollar Sign): Matches the end of a string.

let pattern = /world$/;
console.log(pattern.test(“hello world”)); // Output: true (because ‘world’ is at the end)

What happens when we use the world at the start.?

let pattern = /world$/;
console.log(pattern.test(“world hello “)); // Output: false (because the world is at the start)

Common Patterns and Their Meanings

1. Matching Any Digit: \d

To match any digit (0-9), we use \d.

let pattern = /\d/;
console.log(pattern.test(“123”)); // Output: true (because ‘123’ contains digits)

What happens when we use letter in pattern.?

let pattern = /\d/;
console.log(pattern.test(“abc”)); // Output: false(because it does not contain any digits)

2. Matching Non-Digits: \D

To match anything except digits, use \D.

let pattern = /\D/;
console.log(pattern.test(“abc”)); // Output: true (because ‘abc’ contains non-digits)

What happens when we use digits.?

let pattern = /\D/;
console.log(pattern.test(“123”));// Output: false (because ‘123’ contains digits)

3. Matching Whitespace: \s

To match any whitespace (spaces, tabs, or line breaks), use \s.

let pattern = /\s/;
console.log(pattern.test(“hello world”)); // Output: true (because there’s a space between ‘hello’ and ‘world’)

What happens when we don’t use any whitespace .?

let pattern = /\s/;
console.log(pattern.test(“helloworld”)); // Output: false (because there isn’t space between ‘hello’ and ‘world’)

4. Matching Non-Whitespace: \S

To match anything except whitespace, use \S.

let pattern = /\S/;
console.log(pattern.test(“hello”)); // Output: true (because ‘hello’ contains non-whitespace characters)

What happens when we use only whitespace.?

let pattern = /\S/;
console.log(pattern.test(” “)); //Output: false (because it contains only whitespace)

5. Matching Word Characters: \w

To match letters, digits, or underscores, use \w.

let pattern = /\w/;
console.log(pattern.test(“hello123”)); // Output: true (because ‘hello123’ contains word characters)

What happens when we use special character.?

let pattern = /\w/;
console.log(pattern.test(“*$@”)); // Output: false (because it does’nt contains word characters)

6. Matching Non-Word Characters: \W

To match anything except letters, digits, or underscores, use \W.

let pattern = /\W/;
console.log(pattern.test(“hello!”)); // Output: true (because ‘!’ is a non-word character)

What happens when we don’t use non-word character.?

let pattern = /\W/;
console.log(pattern.test(“hello”)); // Output: false (because it does contain any non-word character)

Quantifiers: How Many Times?

Sometimes, you want to specify how many times something should occur. You can do this with quantifiers.

1. * (Asterisk)

Meaning: Matches 0 or more occurrences of the preceding element.

Use Case: You can use this quantifier when you want to match an element (like a character or group) multiple times, including zero occurrences.

Example:

const regex = /a*/;
console.log(regex.test(“aaa”)); // true (matches “aaa”)
console.log(regex.test(“”)); // true (matches the empty string, 0 occurrences of “a”)
console.log(regex.test(“b”)); // true (matches 0 occurrences of “a”)

2. + (Plus)

Meaning: Matches 1 or more occurrences of the preceding element.

Use Case: This quantifier is used when you want to ensure that the element appears at least once, but it can occur more times.

Example:

const regex = /a+/;
console.log(regex.test(“aaa”)); // true (matches “aaa”)
console.log(regex.test(“a”)); // true (matches “a”)
console.log(regex.test(“”)); // false (no “a” in the string)

3. ? (Question Mark)

Meaning: Matches 0 or 1 occurrence of the preceding element.

Use Case: This is used when you want to optionally match a character or group. It will match the element if it exists, and it will also match the absence of the element.

Example:

const regex = /a?/;
console.log(regex.test(“a”)); // true (matches “a”)
console.log(regex.test(“”)); // true (matches 0 occurrences of “a”)
console.log(regex.test(“b”)); // true (matches 0 occurrences of “a”)

4. {n} (Exact number of occurrences)

Meaning: Matches exactly n occurrences of the preceding element.

Use Case: This quantifier ensures that the element appears exactly n times.

Example:

const regex = /a{3}/;
console.log(regex.test(“aaa”)); // true (exactly 3 “a”s)
console.log(regex.test(“aa”)); // false (only 2 “a”s)
console.log(regex.test(“aaaa”)); // false (more than 3 “a”s)

5. {n,} (At least n occurrences)

Meaning: Matches at least n occurrences of the preceding element, but it can match more.

Use Case: This quantifier is used when you want to match an element n or more times.

Example:

const regex = /a{2,}/;
console.log(regex.test(“aa”)); // true (matches exactly 2 “a”s)
console.log(regex.test(“aaa”)); // true (matches 3 “a”s)
console.log(regex.test(“a”)); // false (only 1 “a”)

6. {n,m} (Between n and m occurrences)

Meaning: Matches between n and m occurrences of the preceding element.

Use Case: This quantifier is used when you want to match an element that appears at least n times but not more than m times.

Example:

const regex = /a{2,4}/;
console.log(regex.test(“aa”)); // true (exactly 2 “a”s)
console.log(regex.test(“aaa”)); // true (exactly 3 “a”s)
console.log(regex.test(“aaaa”)); // true (exactly 4 “a”s)
console.log(regex.test(“a”)); // false (only 1 “a”)
console.log(regex.test(“aaaaa”)); // false (more than 4 “a”s)

Matching Options with |

If you want to match either one thing or another, you can use the pipe (|), which means “or”.

let pattern = /cat|dog/;
console.log(pattern.test(“I love cats”)); // Output: true (because ‘cat’ is matched)

Using Regular Expressions in JavaScript

In JavaScript, you can use RegEx in many ways:

 test(): Returns true if the pattern matches, otherwise false.

let pattern = /apple/;

let text = “I like apple pie.”;

console.log(pattern.test(text));  // Output: true

  exec(): Returns an array with the match, or null if no match is found.

let pattern = /apple/;
let text = “I like apple pie.”;
console.log(pattern.exec(text)); // Output: [‘apple’]

  replace(): Replaces matched text with something else.

let text = “I love apples!”;
let newText = text.replace(/apple/, “orange”);
console.log(newText); // Output: “I love oranges!”

1. Real-World Example: Validating an Email Address

Regular expressions are very useful for checking if an email address is correctly formatted.

let pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
let email = “test@example.com”;
console.log(pattern.test(email)); // Output: true (because it’s a valid email)

Code Explanation:

Regular Expression Explanation

let pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;

1. ^:

•  This symbol marks the beginning of the string.
•  It ensures that the match starts from the very beginning of the email address.

2. [a-zA-Z0-9._-]+:

  This part matches the username part of the email (before the @ symbol).
  a-zA-Z0-9: Matches any lowercase (a-z), uppercase (A-Z), or digit (0-9).
•  ._-: Matches the dot (.), underscore (_), and hyphen (-) characters in the username part.
•  The + means that this pattern must appear one or more times (the username part must have at least one character, but can have many).

3. @:

  This part matches the username part of the email (before the @ symbol).
  a-zA-Z0-9: Matches any lowercase (a-z), uppercase (A-Z), or digit (0-9).
•  ._-: Matches the dot (.), underscore (_), and hyphen (-) characters in the username part.
•  The + means that this pattern must appear one or more times (the username part must have at least one character, but can have many).

4. [a-zA-Z0-9.-]+:

  This part matches the domain part of the email (after the @ symbol and before the dot .).
  a-zA-Z0-9: Matches any letter or digit.
  .-: Matches dot (.) and hyphen (-) characters in the domain name.
  The + again means that this pattern must appear one or more times (the domain part must have at least one character, but can have many).

5. \.:

  The backslash (\) is used to escape the dot (.) character because in regular expressions, the dot represents any character.
  This ensures that it matches a literal dot (.), which is part of the domain name in email addresses (e.g., example.com).

6. [a-zA-Z]{2,6}:

  This matches the domain extension (like .com, .org, etc.).
•  a-zA-Z: Matches any letter (uppercase or lowercase).
  {2,6}: Specifies that the domain extension must have at least 2 characters and at most 6 characters (for example, .com, .org, .co.uk).

7. $:

  This symbol marks the end of the string.
•  It ensures that there are no extra characters after the domain extension.

Code Explanation:

let pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
let email = “test@example.com”;
console.log(pattern.test(email)); // Output: true (because it’s a valid email)

Explanation of the Code:

email = “test@example.com”: This is the email address we want to check.

pattern.test(email):

•  test() is a method used on regular expressions to check if a string matches the pattern.
  It returns true if the string matches the pattern and false if it does not.

Output
Explanation-of-the-code

true: The email “test@example.com” matches the pattern, meaning it is a valid email address according to the specified regular expression.

Example of Invalid Emails:

let invalidEmail1 = “test@.com”; // Invalid: domain is missing
let invalidEmail2 = “test@com”; // Invalid: no dot before domain extension
console.log(pattern.test(invalidEmail1)); // Output: false
console.log(pattern.test(invalidEmail2)); // Output: false

Output

These examples will output false because they don’t match the pattern for a valid email address.

2. Phone Number Validation

Regular expressions can be used to validate phone numbers in various formats, for example, US phone numbers.

Example:

const phoneRegex = /^\(?(\d{3})\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;

const testPhones = [
“(123) 456-7890”, // Valid
“123-456-7890”, // Valid
“123.456.7890”, // Valid
“123 456 7890”, // Valid
“123-45-7890”, // Invalid
];

testPhones.forEach(phone => {
console.log(`${phone}: ${phoneRegex.test(phone)}`);
});

Code Explanation:

1. Regex Breakdown:

/^\(?(\d{3})\)?[-.\s]?\d{3}[-.\s]?\d{4}$/

This regex is designed to match phone numbers that can have:

An optional area code is enclosed in parentheses.

Hyphens (-), dots (.), or spaces (\s) as separators.

Exactly 10 digits, grouped into three sets: (xxx) xxx-xxxx or xxx-xxx-xxxx, etc.

Detailed Explanation of the Regex:

1. ^:

Anchors the regex at the start of the string. It means the match must start from the beginning of the string.

2. \(?(\d{3})\)?:

\(?: Matches an optional opening parenthesis (. The backslash (\) escapes the parenthesis to treat it literally.

(\d{3}): Matches exactly 3 digits (\d stands for any digit, {3} specifies exactly 3 occurrences). This is for the area code of the phone number.

\)?: Matches an optional closing parenthesis ).

The area code can optionally be enclosed in parentheses (e.g., (123)), or it can appear without parentheses (e.g., 123).

3. [-.\s]?:

[-.\s]: Matches any of the following characters:

-: Hyphen

.: Dot

\s: A space character (whitespace).

?: The question mark means that the separator is optional, meaning it could be present or absent.

4. \d{3}:

Matches exactly 3 digits for the second part of the phone number (e.g., 456 in 123-456-7890).

5. [-.\s]?:

Same as the earlier part, this matches an optional separator (hyphen, dot, or space) between the second and third parts of the phone number.

6. \d{4}:

Matches exactly 4 digits for the final part of the phone number (e.g., 7890 in 123-456-7890).

7. $:

Anchors the regex at the end of the string. It ensures that the match must end at the end of the string.

2. Test Phone Numbers:

The testPhones array contains various phone numbers in different formats. We will use the .test() method to check if the regex matches each phone number:

const testPhones = [
“(123) 456-7890”, // Valid
“123-456-7890”, // Valid
“123.456.7890”, // Valid
“123 456 7890”, // Valid
“123-45-7890”, // Invalid
];

3. Test the Regex:

We iterate over each phone number in the testPhones array and use phoneRegex.test(phone) to check whether the phone number matches the pattern:

testPhones.forEach(phone => {
console.log(`${phone}: ${phoneRegex.test(phone)}`);
});

For each phone number, the .test() method returns:

true if the regex matches the phone number.

false if the regex does not match the phone number.

Output
Phone-number-validation

3. Password Strength Validation

Regular expressions can be used to validate phone numbers in various formats, for example, US phone numbers.

const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$/;

const testPasswords = [
“P@ssw0rd”, // Valid
“password”, // Invalid (no uppercase, no special char)
“P@sswrd”, // Invalid (no number)
“1234abcd”, // Invalid (no special char, no uppercase)
“P@ssw0rd123” // Valid
];

testPasswords.forEach(password => {
console.log(`${password}: ${passwordRegex.test(password)}`);
});

1. Regular Expression Breakdown:

/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$/

This regular expression enforces the following password requirements:

At least one lowercase letter (a-z).

At least one uppercase letter (A-Z).

At least one digit (0-9).

At least one special character from the set !@#$%^&*.

Minimum length of 8 characters.

Detailed Explanation of the Regex:

1. ^:

Anchors the regex to the start of the string. It ensures the match starts from the beginning.

2. (?=.*[a-z]):

This is a positive lookahead (?=) that checks for at least one lowercase letter anywhere in the string.

[a-z] matches any lowercase letter.

.* means “zero or more characters” before the lowercase letter, allowing it to appear anywhere in the string.

3. (?=.*[A-Z]):

Another positive lookahead that checks for at least one uppercase letter.

[A-Z] matches any uppercase letter.

.* means “zero or more characters” before the uppercase letter.

4. (?=.*\d):

This positive lookahead checks for at least one digit (\d matches any digit, equivalent to [0-9]).

.* allows other characters to appear before the digit.

5. (?=.*[!@#$%^&*]):

This positive lookahead checks for at least one special character from the set !@#$%^&*.

[!@#$%^&*] matches any of these special characters.

.* allows other characters before the special character.

6. [A-Za-z\d!@#$%^&*]{8,}:

This part matches the actual characters in the password.

[A-Za-z\d!@#$%^&*] allows:

Uppercase letters (A-Z),

Lowercase letters (a-z),

Digits (0-9),

Special characters from the set !@#$%^&*.

{8,} ensures that there are at least 8 characters in the password. The {8,} means “8 or more occurrences of the allowed characters.”

7. $:

Anchors the regex to the end of the string. It ensures the match must go all the way to the end of the string, making sure the password has exactly the required characters (no extra characters).

2. Test Passwords:

The testPasswords array contains various example passwords to test against the regex:

const testPasswords = [
“P@ssw0rd”, // Valid
“password”, // Invalid (no uppercase, no special char)
“P@sswrd”, // Invalid (no number)
“1234abcd”, // Invalid (no special char, no uppercase)
“P@ssw0rd123” // Valid
];

Each password in this array is checked using the .test() method, which returns true if the password matches the regex (i.e., it satisfies the conditions) and false if it does not

3. Test the Regex:

The forEach loop iterates over each password in the testPasswords array and checks if it matches the regex using passwordRegex.test(password):

testPasswords.forEach(password => {
console.log(`${password}: ${passwordRegex.test(password)}`);
});

This will print out whether each password is valid (true) or invalid (false).

Output
Password-strength

Course Video

Practice Scenario:

You have to solve all the questions given below in the editor without copy-pasting.

1. Using Regular Expression check whether the text has a Following Pattern or not and print in a document.

The task is to use a Regular Expression to check whether a given text matches a specific pattern and then print the result in a document.

 

1. Regular Expression (RegExp): A Regular Expression is a sequence of characters that defines a search pattern. It can be used to perform pattern matching within strings.
2. Check for a Specific Pattern:
You’ll be given a specific pattern that the text needs to match. For example, the pattern could be a certain combination of letters, numbers, or symbols.
3. Using RegExp to Test:
– You need to use JavaScript’s RegExp object or the RegExp literal syntax to create a Regular Expression with the specified pattern.
– Then, use the test() method of the RegExp object to check whether the given text matches the pattern.
4. Display Result in a Document:
– If the text matches the pattern, print a message like “Pattern Found” or display the matched content in a document.
– If the text doesn’t match the pattern, print a message like “Pattern Not Found” or handle it accordingly.

Test Sentence: I love apples!
Pattern word: apple

Here's an example program:

// Example: Check if the text contains the word “apple”
const textToCheck = “I love apples!”;
const patternToMatch = /apple/;

if (patternToMatch.test(textToCheck)) {
document.write(“Pattern Found: ” + textToCheck);
} else {
document.write(“Pattern Not Found”);
}

Output

2. Write a JS Program to Take the Mobile Number From the User using Input Type Text and Validate the Input Using Regular Expression if the User Enter Mobile Number Less than or Greater Than 10 then the Error message will be Print on the Document and if the User Enter Alphabet then also it will show Error on Document.

The task is to write a JavaScript program that takes a mobile number from the user using an input type text and validates the input using Regular Expressions (RegExp). If the user enters a mobile number with less than or greater than 10 digits, or if they enter alphabets, an error message should be displayed on the document.

1. HTML Input: Create an HTML input element of type text to take the mobile number from the user.
2. JavaScript Validation:
– Write JavaScript code to handle the validation.
– Use a Regular Expression to check if the input contains only digits (numbers).
– Validate the length of the input to ensure it has exactly 10 digits.
– Display an error message on the document if the validation fails.

Here's an example program:

<!DOCTYPE html>
<html >
<head>
<title>Mobile Number Validation</title>
</head>
<body>
<label for=”mobileNumber”>Enter Mobile Number:</label>
<input type=”text” id=”mobileNumber” placeholder=”Enter 10-digit mobile number”>
<button onclick=”validateMobileNumber()”>Validate</button>
<p id=”error-message”></p>

<script>
// JavaScript code
function validateMobileNumber() {
// Get the mobile number input value
const mobileNumber = document.getElementById(“mobileNumber”).value;

// Regular Expression to match only digits
const digitRegExp = /^\d+$/;

// Check if the input contains only digits and has exactly 10 digits
if (digitRegExp.test(mobileNumber) && mobileNumber.length === 10) {
document.getElementById(“error-message”).innerText = “”; // Clear error message
document.write(“Mobile Number is Valid: ” + mobileNumber);
} else {
// Display an error message
document.getElementById(“error-message”).innerText = “Invalid Mobile Number”;
}
}
</script>
</body>
</html>

Output

2. Write a JS Program to Take the Mobile Number From the User using Input Type Text and Validate the Input Using Regular Expression if the User Enter Mobile Number Less than or Greater Than 10 then the Error message will be Print on the Document and if the User Enter Alphabet then also it will show Error on Document.

The task is to create a JavaScript program that takes an email ID from the user using an input type text and validates the input using Regular Expressions (RegExp). The program should check if the user input contains certain essential components of an email address (like “@” and “.com”), as well as specific domains (like “gmail”), and numerical characters. If any of these components are missing or not in the proper format, an error message should be displayed on the document.

1. HTML Input:
Create an HTML input element of type text to take the email ID from the user.
2. JavaScript Validation:
– Write JavaScript code to handle the validation.
– Use Regular Expressions to check if the input contains “@” and “.com”, as well as the presence of specific domains like “gmail”.
– Validate if the email contains numerical characters.
– Display an error message on the document if any of the validation checks fail.

Here's an example program:

<!DOCTYPE html>
<html >
<head>
<title>Email Validation</title>
</head>
<body>
<label for=”email”>Enter Email ID:</label>
<input type=”text” id=”email” placeholder=”Enter your email”>
<button onclick=”validateEmail()”>Validate</button>
<p id=”error-message”></p>

<script>
// JavaScript code
function validateEmail() {
// Get the email input value
const email = document.getElementById(“email”).value;

// Regular Expressions for email validation
const emailRegExp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
const domainRegExp = /@gmail\.com$/; // Check if the email contains the domain “gmail.com”

// Check if the input matches the required patterns
if (emailRegExp.test(email) && domainRegExp.test(email)) {
document.getElementById(“error-message”).innerText = “”; // Clear error message
document.write(“Email ID is Valid: ” + email);
} else {
// Display an error message
document.getElementById(“error-message”).innerText = “Invalid Email ID”;
}
}
</script>
</body>
</html>

Output

4. Write a JS Program To Take Input From the User as "I am Learning HTML" and Replace the HTML with Javascript using Regular Expression.

The task is to create a JavaScript program that takes input from the user as “I am Learning HTML” and replaces the word “HTML” with “JavaScript” using Regular Expressions.

1. HTML Input:
You can use an HTML input element of type text to take the input from the user.
2. JavaScript Replacement:
– Write JavaScript code to handle the replacement.
– Use Regular Expressions to match the word “HTML” in the input string.
– Replace “HTML” with “JavaScript” using the replace method.

Here's an example program:

<!DOCTYPE html>
<html>
<head>
<title>String Replacement</title>
</head>
<body>
<label for=”inputText”>Enter Text:</label>
<input type=”text” id=”inputText” placeholder=”Enter text”>
<button onclick=”replaceText()”>Replace</button>
<p id=”result”></p>

<script>
// JavaScript code
function replaceText() {
// Get the input text value
const inputText = document.getElementById(“inputText”).value;

// Regular Expression to match the word “HTML”
const htmlRegExp = /\bHTML\b/;

// Replace “HTML” with “JavaScript”
const resultText = inputText.replace(htmlRegExp, “JavaScript”);

// Display the result
document.getElementById(“result”).innerText = “Replaced Text: ” + resultText;
}
</script>
</body>
</html>

Output
Frequently Asked Questions

Still have a question?

Let's talk

A regular expression (regex) is a sequence of characters used to define a search pattern, typically for string matching and manipulation. Learn more in our JavaScript regular expression free course video.

Regular expressions can be created using:

  • Literal notation: /pattern/flags
  • Constructor: new RegExp(“pattern”, “flags”)
    Explore these methods in the JS regular expression with free video tutorial.
  • g: Global search.
  • i: Case-insensitive search.
  • m: Multi-line search.
    Discover their usage in the Free JavaScript regular expression tutorial for beginners.

Use the test() method.
Example:

let regex = /abc/; 

console.log(regex.test(“abcdef”)); // Output: true 

Learn step-by-step in the JavaScript regular expressions with free tutorial.

Use the match() method.
Example:

let str = “The rain in Spain”; 

let matches = str.match(/ain/g); 

console.log(matches); // Output: [“ain”, “ain”] 

Watch practical examples in the JavaScript regular expression free course video.

Yes, use the replace() method.
Example:

let str = “Hello World”; 

let result = str.replace(/World/, “JavaScript”); 

console.log(result); // Output: Hello JavaScript 

Discover more in the JS regular expression with free video tutorial.

Use a backslash (\) before the special character.
Example:

let regex = /\*/; // Matches a literal asterisk (*) 

Learn about this in the Free JavaScript regular expression tutorial for beginners.

  • +: Matches one or more occurrences of the preceding element.
  • *: Matches zero or more occurrences.
    Explore their differences in the JavaScript regular expressions with free tutorial.

Yes, a regex pattern like this can be used:

let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; 

Check this out in the JavaScript regular expression free course video.

  • Avoid overly complex patterns as they can impact performance.
  • Use specific patterns to reduce backtracking.
  • Test regex patterns thoroughly for efficiency.
    Find best practices in the JS regular expression with free video tutorial.