RegExp.prototype.exec() मेथड स्ट्रिंग में मैच के लिए खोज करता है। मैच मिलने पर परिणाम एरे लौटाता है, अन्यथा null। g फ्लैग के साथ यह पुनरावृत्त खोज सक्षम करता है।
उदाहरण
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
.sample { font-size: 18px; font-weight: 500; padding: 15px; background: #f8f9fa; border-radius: 4px; }
button { padding: 10px 20px; background: #6f42c1; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style> </head> <body>
<h1>JavaScript RegExp exec() मेथड</h1>
<div class="sample">Lorem ipsum dolor, sit amet consectetur adipisicing.</div>
<button class="Btn">रेगेक्स निष्पादित करें</button>
<h3>ऊपर दिए गए बटन पर क्लिक करके 'amet' के लिए रेगेक्स निष्पादित करें</h3>
<script>
const sampleEle = document.querySelector(".sample");
const sampleStr = sampleEle.innerHTML;
const pattern = new RegExp("amet");
document.querySelector(".Btn").addEventListener("click", () => {
const result = pattern.exec(sampleStr);
if (result) {
sampleEle.innerHTML += ` <br> मिला: "${result[0]}" इंडेक्स ${result.index} पर`;
} else {
sampleEle.innerHTML += " <br> कोई मैच नहीं मिला";
}
});
</script> </body> </html>
आउटपुट
क्लिक करने पर: मिला: "amet" इंडेक्स 32 पर
exec() परिणाम एरे संरचना
const regex = /(\w+)\s(\w+)/; const str = "Hello World"; const result = regex.exec(str); console.log(result[0]); // "Hello World" (पूरा मैच) console.log(result[1]); // "Hello" (पहला कैप्चर ग्रुप) console.log(result[2]); // "World" (दूसरा कैप्चर ग्रुप) console.log(result.index); // 0 (मैच का इंडेक्स) console.log(result.input); // "Hello World" (मूल स्ट्रिंग) console.log(result.groups); // नेम्ड कैप्चर ग्रुप्स (यदि उपयोग किए गए)
ग्लोबल फ्लैग (g) के साथ पुनरावृत्ति
const str = "cat bat rat cat";
const regex = /\w{3}/g; // 3 अक्षर वाले शब्द
let match;
while ((match = regex.exec(str)) !== null) {
console.log(`मिला: "${match[0]}" इंडेक्स ${match.index} पर`);
// अंतिम इंडेक्स regex.lastIndex में संग्रहीत होता है
}
// आउटपुट:
// मिला: "cat" इंडेक्स 0 पर
// मिला: "bat" इंडेक्स 4 पर
// मिला: "rat" इंडेक्स 8 पर
// मिला: "cat" इंडेक्स 12 पर
match() vs exec()
| विशेषता | String.match() | RegExp.exec() |
|---|---|---|
| कॉल किया जाता है | स्ट्रिंग पर | रेगेक्स पर |
| g फ्लैग के बिना | पहला मैच एरे | पहला मैच एरे |
| g फ्लैग के साथ | सभी मैच का एरे | पुनरावृत्त (लूप में) |
| कैप्चर ग्रुप्स | g के साथ नहीं | हमेशा उपलब्ध |