JavaScript: Step 11- Regular Expressions

Regular expressions (also known as regex or regexp) are patterns used to match character combinations in strings. They are commonly used for text search and text replace operations.

In JavaScript, regular expressions are objects that can be created using the RegExp constructor or by using the literal notation /pattern/.

Tabular Comparisons:

Literal notationConstructor notation
/pattern/new RegExp('pattern')
i flag for case-insensitive matching: /pattern/inew RegExp('pattern', 'i')
g flag for global matching: /pattern/gnew RegExp('pattern', 'g')
m flag for multiline matching: /pattern/mnew RegExp('pattern', 'm')

Text Diagram:

String
  |
RegExp Object
  |
Pattern Matching

Basic Programs:

  1. Matching a string using a regular expression:
const pattern = /hello/;
const str = 'Hello, World!';
const result = pattern.test(str);
console.log(result); // false

  1. Using the exec() method to find matches in a string:
const pattern = /hello/g;
const str = 'Hello, World! Hello, JavaScript!';
let result;
while ((result = pattern.exec(str)) !== null) {
	console.log(result[0]);
}
// Output: "Hello" "Hello"
  1. Replacing text using a regular expression:
const pattern = /hello/gi;
const str = 'Hello, World! Hello, JavaScript!';
const newStr = str.replace(pattern, 'Hi');
console.log(newStr); // "Hi, World! Hi, JavaScript!"

To run these programs in Visual Studio Code, create a JavaScript file with a .js extension and use Node.js to execute the file. For example:

// test.js
const pattern = /hello/;
const str = 'Hello, World!';
const result = pattern.test(str);
console.log(result); // false

// Open a terminal window in Visual Studio Code
// Navigate to the directory containing the test.js file
// Run the file using Node.js
// Command: node test.js
  1. Using regular expressions to validate user input:
const pattern = /^[a-zA-Z\s]+$/;
const input = 'John Doe';
const isValid = pattern.test(input);
console.log(isValid); // true

This program validates whether the input string contains only letters (uppercase or lowercase) and whitespace.

  1. Splitting a string using a regular expression:
const pattern = /\s+/;
const str = 'Hello, World! How are you?';
const words = str.split(pattern);
console.log(words); // ["Hello,", "World!", "How", "are", "you?"]


This program splits the string into an array of words, using whitespace as the delimiter.

Note: Regular expressions can be complex and may require some practice to master. The examples provided here are basic and intended to give an introduction to regular expressions in JavaScript.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.