परिचय
जावास्क्रिप्ट में रेगुलर एक्सप्रेशन्स के साथ काम करने के लिए दो मुख्य मेथड्स हैं: test() (बूलियन लौटाता है) और exec() (विस्तृत मिलान जानकारी के साथ ऐरे लौटाता है)।
उदाहरण
निम्न कोड जावास्क्रिप्ट में रेगुलर एक्सप्रेशन को टेस्ट और एक्जीक्यूट करने के लिए है:
<!DOCTYPE html> <html lang="hi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>रेगएक्स टेस्ट और एक्जीक्यूट</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result, .sample { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>रेगुलर एक्सप्रेशन्स टेस्ट और एक्जीक्यूट करना</h1> <div class="sample"></div> <div style="color: green;" class="result"></div> <button class="Btn">यहाँ क्लिक करें</button> <h3> रेगुलर एक्सप्रेशन को टेस्ट और एक्जीक्यूट करने के लिए ऊपर दिए गए बटन पर क्लिक करें </h3> <script> const sampleEle = document.querySelector('.sample'); const resEle = document.querySelector('.result'); const str = 'Hello world. This is a beautiful world'; sampleEle.innerHTML = str; const pattern = new RegExp("world"); document.querySelector(".Btn").addEventListener("click", () => { resEle.innerHTML += 'pattern.test(str) = ' + pattern.test(str) + '<br>'; resEle.innerHTML += 'pattern.exec(str) = ' + JSON.stringify(pattern.exec(str)) + '<br>'; }); </script> </body> </html>
आउटपुट
उपरोक्त कोड निम्न आउटपुट उत्पन्न करेगा:

'यहाँ क्लिक करें' बटन पर क्लिक करने पर:

मेथड तुलना
| मेथड | रिटर्न | उपयोग |
|---|---|---|
regex.test(str) | बूलियन | त्वरित जांच: क्या पैटर्न मौजूद है? |
regex.exec(str) | ऐरे या null | विस्तृत जानकारी: मिलान, इंडेक्स, ग्रुप्स |
str.match(regex) | ऐरे या null | स्ट्रिंग मेथड, g फ्लैग के साथ सभी मिलान |
str.matchAll(regex) | इटरेटर | सभी मिलान विस्तृत जानकारी के साथ (ES2020) |
exec() रिटर्न वैल्यू विवरण
const match = /(\w+)\s(\w+)/.exec('Hello World');
// match[0] = 'Hello World' (पूरा मिलान)
// match[1] = 'Hello' (पहला कैप्चर ग्रुप)
// match[2] = 'World' (दूसरा कैप्चर ग्रुप)
// match.index = 0 (मिलान का इंडेक्स)
// match.input = 'Hello World' (मूल स्ट्रिंग)
// match.groups = { ... } (नेम्ड ग्रुप्स, यदि कोई हो)