RegExp Usage
Match and extract text with regular expressions.
Code
JavaScript
const text = "Contact: john@example.com or jane@test.org";
const pattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
const matches = text.match(pattern);
console.log(matches); // ["john@example.com", "jane@test.org"]
// With exec
const re = new RegExp(pattern);
let m;
while ((m = re.exec(text)) !== null) {
console.log(m[0], m.index);
}Line-by-line explanation
- 1.String.match() returns array of matches (or null).
- 2.RegExp with g flag for global match.
- 3.exec() in loop for match + index.
Expected output
["john@example.com", "jane@test.org"]