JavaScript Regular Expressions
Regular expressions are a powerful tool for working with strings in JavaScript, enabling you to search, match, and manipulate text with ease. In this blog post, we’ll dive into JavaScript regular expressions, with examples ranging from basic to advanced.
“Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.” — Jamie Zawinski
Basic Regular Expressions
Regular expressions are patterns used to match character combinations in strings. They can be created using the RegExp constructor or with literal syntax.
Basic Example:
const pattern1 = /hello/;
const pattern2 = new RegExp("hello");
const text = "Hello, world!";
console.log(pattern1.test(text)); // false
console.log(pattern2.test(text.toLowerCase())); // trueIn this example, we create two regular expressions to match the word “hello” and test them against a string.
Using Flags
Flags can be added to regular expressions to modify their behavior, such as making them case-insensitive or global.
Get JavaScript-World’s stories in your inbox
Join Medium for free to get updates from this writer.
Basic Example:
const pattern = /hello/i; // Case-insensitive flag
const text = "Hello, world!";
console.log(pattern.test(text)); // trueIn this example, we add the case-insensitive flag (i) to our regular expression, which allows it to match the string regardless of the case.
Groups and Capturing
You can use parentheses to create groups and capture portions of a match.
Advanced Example:
const pattern = /(\d{4})-(\d{2})-(\d{2})/;
const text = "The date is 2021-10-22.";
const match = pattern.exec(text);
console.log(match[0]); // "2021-10-22"
console.log(match[1]); // "2021"
console.log(match[2]); // "10"
console.log(match[3]); // "22"In this example, we create a regular expression with three capturing groups to extract the year, month, and day from a date string.
Conclusion
JavaScript regular expressions are a powerful tool for working with strings, allowing you to search, match, and manipulate text with precision. By mastering the basics of regular expressions and exploring their advanced features, you can elevate your string manipulation skills in JavaScript.
If you enjoyed the article and would like to show your support, be sure to:
👏 Applaud for the story (50 claps) to help this article get featured
👉Follow me on Medium
Check out more content on my Medium profile





