JS Regular Expression

HTML
CSS
C#
SQL

RegExp Reference

A regular expression (RegExp) in JavaScript is a powerful tool for pattern matching within strings. It is commonly used for search-and-replace operations and text validation. A RegExp object in JavaScript consists of properties and methods that facilitate working with patterns.

Syntax:

A regular expression is defined using the following syntax:

/pattern/modifiers;

For example:

let pattern = /Technology/i;

Here, /Technology/ is the pattern, and i is a modifier indicating a case-insensitive match.

Creating a RegEx:

There are two ways to create a regular expression in JavaScript.

1. Using a regular expression literal:

The regular expression is represented by a pattern enclosed between slashes /.

   const regexLiteral = /abc/;

2. Using the RegExp() constructor function:

You can create a regular expression by calling the RegExp() constructor function.

   const regexConstructor = new RegExp(‘abc’);

For example,

Modifiers:

Modifiers are optional flags that affect the behaviour of a regular expression. Common modifiers include:

– g: Perform a global match (find all matches rather than stopping after the first match).
– i: Perform case-insensitive matching.
– m: Perform multiline matching.

Example:

const regex = new RegExp(/^a…s$/);
document.write (regex.test(‘alias’)); // true

Brackets:

Brackets are used to define character classes within a regular expression.

– [abc]: Find any character between the brackets.
– [^abc]: Find any character NOT between the brackets.
– [0-9]: Find any digit.
– [^0-9]: Find any non-digit.
– (x|y): Find any of the alternatives specified.

Example:

const digitRegex = /[0-9]/;
document.write(digitRegex.test(‘abc123’)); // true

Quantifiers:

Quantifiers specify the number of occurrences of a character or group in a pattern.

– *: Matches zero or more occurrences.
– +: Matches one or more occurrences.
– ?: Matches zero or one occurrence.
– {n}: Matches exactly n occurrences.
– {n,}: Matches n or more occurrences.
– {n,m}: Matches between n and m occurrences.

Example:

const quantifierRegex = /\d{2,4}/;
document.write(quantifierRegex.test(‘12345’)); // true

Anchors:

Anchors define the position in the string where a match should occur.

– ^: Matches the beginning of a string.
– $: Matches the end of a string.

Example:

const anchorRegex = /^start/;
document.write (anchorRegex.test(‘start with regex’)); // true

Escape Characters:

Some characters have special meanings in regular expressions, and to match them literally, you need to escape them with a backslash \.

– \.: Matches a literal dot.
– \\: Matches a literal backslash.

Example:

const escapeRegex = /\d+\.\d+/;
document.write (escapeRegex.test(‘3.14’)); // true

Capture Groups:

Capture groups are portions of a pattern enclosed in parentheses, allowing you to extract matched substrings.

Assertions:

Assertions are conditions that must be met at a specific point in the pattern.

– (?=…): Positive lookahead assertion.
– (?<=…): Positive lookbehind assertion.
– (?!…): Negative lookahead assertion.
– (?<!…): Negative lookbehind assertion.

Example:

const lookaheadRegex = /\w+(?=\s)/;
document.write (‘Word followed by space’.match(lookaheadRegex)); // [“Word”]

Course Video

Examples for Practice

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

3. Write a JS Program to Take an Email ID From the User using Input Type Text and Validate the Input Using Regular Expression if the User Input does not contain the following things (“@”, “.com”, “gmail”, “Number”) which are available in Email and in a Proper way Then 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