Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the use of test() method in JavaScript?
The test() method is a regular expression method that searches a string for a pattern and returns true or false, depending on whether the pattern is found. It is case sensitive and provides a simple way to check if a string matches a regular expression pattern.
Syntax
regexPattern.test(string)
Parameters
- string - The string to be tested against the regular expression pattern
Return Value
Returns true if the pattern is found in the string, false otherwise.
Example 1: Pattern Found (Case Match)
In this example, we check if the pattern "Tu" exists in the text. Since the pattern matches exactly, the method returns true.
<html>
<body>
<p id="text">Tutorix is the best e-learning platform</p>
<p id="test"></p>
<script>
var text = document.getElementById("text").innerHTML;
document.getElementById("test").innerHTML = /Tu/.test(text);
</script>
</body>
</html>
Tutorix is the best e-learning platform true
Example 2: Pattern Not Found (Case Sensitivity)
Here we check for the pattern "tu" (lowercase). Since the text contains "Tu" (uppercase) and the test() method is case sensitive, it returns false.
<html>
<body>
<p id="text">Tutorix is the best e-learning platform</p>
<p id="test"></p>
<script>
var text = document.getElementById("text").innerHTML;
document.getElementById("test").innerHTML = /tu/.test(text);
</script>
</body>
</html>
Tutorix is the best e-learning platform false
Example 3: Case-Insensitive Testing
To perform case-insensitive testing, use the i flag in your regular expression.
<html>
<body>
<p id="text">Tutorix is the best e-learning platform</p>
<p id="test"></p>
<script>
var text = document.getElementById("text").innerHTML;
document.getElementById("test").innerHTML = /tu/i.test(text);
</script>
</body>
</html>
Tutorix is the best e-learning platform true
Common Use Cases
- Email validation
- Phone number format checking
- Password strength validation
- Input field validation in forms
Conclusion
The test() method is essential for pattern matching in JavaScript. It provides a simple boolean result, making it perfect for validation tasks and conditional logic based on string patterns.
