Regular expressions (regex) in JavaScript are patterns used to match character combinations in strings. They provide a powerful and flexible way to search, replace, and validate strings. Here are some common operations and examples of using regular expressions in JavaScript:
1. Matching a specific pattern:
let str = "Hello, World!"; let pattern = /World/; console.log(pattern.test(str)); // Output: true
2. Matching any character:
let str = "apple"; let pattern = /./; // Matches any single character console.log(pattern.test(str)); // Output: true
3. Matching a character set:
let str = "hello"; let pattern = /[aeiou]/; // Matches any vowel console.log(pattern.test(str)); // Output: true
4. Matching repetitions:
let str = "12345";
let pattern = /\d{3}/; // Matches three digits
console.log(pattern.test(str)); // Output: true
5. Matching word boundaries:
let str = "Hello world"; let pattern = /\bHello\b/; // Matches "Hello" only if it's a whole word console.log(pattern.test(str)); // Output: true
6. Replacing text:
let str = "Hello, world!"; let newStr = str.replace(/world/i, "Universe"); // Case-insensitive replacement console.log(newStr); // Output: "Hello, Universe!"
7. Splitting strings:
let str = "apple,banana,orange"; let fruits = str.split(/,/); // Split by comma console.log(fruits); // Output: ["apple", "banana", "orange"]
8. Validating input:
let str = "12345";
let pattern = /^\d{5}$/; // Validates a 5-digit number
console.log(pattern.test(str)); // Output: true
Regular expressions in JavaScript are versatile and can be combined and customized to match a wide range of patterns in strings.
Code Compiler Link: https://app.singhteekam.in/codecompiler/