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 notation | Constructor notation |
---|---|
/pattern/ | new RegExp('pattern') |
i flag for case-insensitive matching: /pattern/i | new RegExp('pattern', 'i') |
g flag for global matching: /pattern/g | new RegExp('pattern', 'g') |
m flag for multiline matching: /pattern/m | new RegExp('pattern', 'm') |
Text Diagram:
String
|
RegExp Object
|
Pattern Matching
Basic Programs:
- Matching a string using a regular expression:
const pattern = /hello/;
const str = 'Hello, World!';
const result = pattern.test(str);
console.log(result); // false
- 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"
- 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
- 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.
- 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.