A Regular Expression (often abbreviated as RegExp or Regex) is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe exactly what you are looking for. Regular expressions are incredibly powerful for searching, replacing, and validating text (like checking if an email address is valid).
A regular expression can be written simply as a pattern enclosed between two forward slashes /.
/pattern/modifiers;
pattern: The text or sequence you want to search for.modifiers: Optional flags that change how the search is performed (e.g., case-insensitive)./intricate/i is a regular expression.
intricate is the pattern to search for.i is a modifier (modifies the search to be case-insensitive).There are two ways to create a RegExp object in JavaScript:
The literal syntax uses forward slashes /. This is evaluated when the script loads and provides better performance.
const regex1 = /hello/i;
You can also use the new RegExp() constructor. This is useful if your pattern is dynamic (e.g., coming from user input or a variable).
const regex2 = new RegExp("hello", "i");
In JavaScript, regular expressions are most commonly used with the built-in String methods search() and replace().
search() with a String vs RegExpThe search() method searches a string for a specified value and returns the position of the match.
let text = "Welcome to IntricateDevo!";// Search using a normal string let n1 = text.search("intricatedevo"); // Returns -1 (case-sensitive, no match)
// Search using a RegExp with the 'i' (case-insensitive) flag let n2 = text.search(/intricatedevo/i); // Returns 11
console.log("String search:", n1); console.log("RegExp search:", n2);
replace() with a String vs RegExpThe replace() method replaces a specified value with another value in a string. Using a regular expression allows you to replace values regardless of case!
let text = "Please visit Microsoft!";// This replaces "microsoft" (case-insensitive) with "IntricateDevo" let newText = text.replace(/microsoft/i, "IntricateDevo");
console.log(newText);
Which of the following is the correct literal syntax to create a regular expression that searches for "apple" in a case-insensitive manner?