RegExp Usage
Match and extract text with regular expressions.
Code
JavaScript
const text = "Contact: [email protected] or [email protected]"; const pattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g; const matches = text.match(pattern); console.log(matches); // ["[email protected]", "[email protected]"] // 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
["[email protected]", "[email protected]"]