RegExp.test() मेथड का उपयोग यह जांचने के लिए किया जाता है कि किसी स्ट्रिंग में कोई मैच होता है या नहीं। यदि मैच होता है तो यह true लौटाता है, अन्यथा false।
उदाहरण
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>RegExp test</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
div { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>JavaScript RegExp test() मेथड</h1>
<div class="sample">The quick brown fox jumps over the lazy dog</div>
<button class="Btn">यहां क्लिक करें</button>
<div class="result"></div>
<h3>ऊपर दिए गए बटन पर क्लिक करके जांचें कि उपरोक्त स्ट्रिंग में 'fox' है या नहीं</h3>
<script>
let fillEle = document.querySelector(".sample");
let result = document.querySelector(".result");
let regex = new RegExp("fox");
let regResult = regex.test(fillEle.innerHTML);
document.querySelector(".Btn").addEventListener("click", () => {
if (regResult) result.innerHTML = "उपरोक्त स्ट्रिंग में fox है";
else result.innerHTML = "उपरोक्त स्ट्रिंग में fox नहीं है";
});
</script>
</body>
</html>
आउटपुट

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

सिंटैक्स:
regexObj.test(string)
- पैरामीटर - टेस्ट करने के लिए स्ट्रिंग
- रिटर्न -
trueअगर मैच मिला,falseअन्यथा - ग्लोबल फ्लैग (g) - अगर सेट है, तो
lastIndexसे खोज शुरू होती है
महत्वपूर्ण व्यवहार - ग्लोबल फ्लैग के साथ:
const regex = /foo/g; const str = 'foo bar foo'; console.log(regex.test(str)); // true (lastIndex = 3) console.log(regex.test(str)); // true (lastIndex = 11) console.log(regex.test(str)); // false (lastIndex = 0, रीसेट) console.log(regex.test(str)); // true (फिर से शुरू)
चेतावनी: ग्लोबल रेगेक्स पर test() बार-बार कॉल करने पर lastIndex बदलता है, जिससे अनपेक्षित परिणाम मिल सकते हैं।
test() vs match() vs search():
| मेथड | रिटर्न | उपयोग |
|---|---|---|
regex.test(str) |
boolean | केवल यह जांचने के लिए कि मैच है या नहीं |
str.match(regex) |
Array या null | मैच्ड कंटेंट/ग्रुप्स प्राप्त करने के लिए |
str.search(regex) |
number (index) | पहले मैच की पोजिशन जानने के लिए |
regex.exec(str) |
Array या null | कैप्चर ग्रुप्स के साथ डिटेल्ड मैच |
व्यावहारिक उदाहरण:
// ईमेल वैलिडेशन
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
function isValidEmail(email) {
return emailRegex.test(email);
}
// फोन नंबर (भारतीय)
const phoneRegex = /^[6-9]\d{9}$/;
console.log(phoneRegex.test('9876543210')); // true
// पासवर्ड स्ट्रेंथ (कम से कम 1 अपरकेस, 1 लोअरकेस, 1 नंबर, 8+ चैरेक्टर्स)
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
console.log(passwordRegex.test('Pass1234')); // true
बेस्ट प्रैक्टिस:
- सरल बूलियन जांच के लिए
test()उपयोग करें (तेज़) - ग्लोबल फ्लैग (
g) के साथtest()उपयोग न करें जब तकlastIndexमैनेज न करें - कॉम्प्लेक्स वैलिडेशन के लिए
match()याexec()उपयोग करें