JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How does regex work in JavaScript?

Asked on Aug 29, 2024

Answer

Regular expressions (regex) in JavaScript are patterns used to match character combinations in strings. They are implemented using the RegExp object or by using regex literals.
// Example of using regex to find all occurrences of "cat" in a string
        const text = "The cat sat on the mat with another cat.";
        const regex = /cat/g;
        const matches = text.match(regex);
        console.log(matches); // Output: ["cat", "cat"]
Additional Comment:
  • The "g" flag in the regex indicates a global search, meaning it will find all matches in the string.
  • You can create regex patterns using literals (e.g., /pattern/) or the RegExp constructor (e.g., new RegExp("pattern")).
  • Regex can be used with methods like "match", "replace", "test", and "exec" for various string operations.
✅ Answered with JavaScript best practices.
← Back to All Questions