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>Document</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() method</h1>
<div class="sample">The quick brown fox jumps over the lazy dog</div>
<button class="Btn">CLICK HERE</button>
<div class="result"></div>
<h3>Click on the above button to check if the above string contains '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 = "The above string contains fox";
else result.innerHTML = "The above string doesn't contain fox";
});
</script>
</body> </html>
আউটপুট
স্ট্রিংয়ে "fox" আছে, তাই: The above string contains fox
ব্যাখ্যা
test()শুধু মached হয়েছে কিনা তা বুলিয়ান রিটার্ন করে- ম্যাচের ডিটেইল (পজিশন, গ্রুপ ক্যাপচার) পেতে
exec()বাmatch()ব্যবহার করুন test()রেজেক্স অবজেক্টেরlastIndexআপডেট করে (গ্লোবাল ফ্ল্যাগ থাকলে)
test() vs match()
const str = "hello world";
const regex = /world/;
regex.test(str); // true (boolean)
str.match(regex); // ["world", index: 6, input: "...", groups: undefined] (array/null)
regex.test(str); // true
regex.test(str); // true (non-global regex)
const globalRegex = /world/g;
globalRegex.test(str); // true
globalRegex.test(str); // false (lastIndex আপডেট হয়েছে!)
সতর্কতা: গ্লোবাল (g) রেজেক্সে test() কল করলে lastIndex পরিবর্তিত হয়, ফলে повтор কলে ভুল ফলাফল দিতে পারে। প্রতিবার নতুন রেজেক্স তৈরি করুন বা lastIndex = 0 রিসেট করুন।