
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use of Test Method in JavaScript
The test() method is a regular expression method. It searches a string for a pattern, and returns true or false, depending on the result. If it encountered the given pattern it returns true, else returns false. It is case sensitive. Let's discuss it in detail.
Example-1
In the following example, a text named "Tutorix is the best e-learning platform" is given and a pattern "Tu" is checked whether it is present or not. Since the pattern is present the test() method returned true as output.
<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>
Output
Tutorix is the best e-learning platform true
Example-2
In the following example, a pattern "tu" is checked whether it is there in the provided text or not. If we clearly observe the text we have "Tu" present there but not "tu". The test() method even checks the case sensitivity. So the method resulted in false and displayed the result as shown in the output.
<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>
Output
Tutorix is the best e-learning platform false