JavaScript test() Method
This tutorial covers the test() method, part of JavaScript's RegExp object. The test() method offers one of of the easiest way to check for the presence of a regular expression pattern inside a string. The test() method is applied on a regular expression, and takes as argument the string of text in which to match the pattern. Arguments passed to test() can either be a quoted literal string, or a string variable.
Unlike the exec() method, which returns null
or an array of matched patterns, the test() method returns true (if it found a match) or false.
This makes the test() method an ideal choice for quick validation, for example, while exec() is best suited for more involved pattern matching operations.
Using the test() Method
The test() method is applied on the regular expression containing the pattern to match; the string in which to match the pattern is the argument passed to test(). The script below checks for the presence of "javascript" inside a test string.
var carter = "I learn JavaScript.";
// Declare a case-insensitive regular expression
var remo = /javascript/i;
if( remo.test(carter) );
alert("You are learning JavaScript");
As expected, the script returned a confirmation:
To easily remember which of the regular expression and string is passed as argument to the test() method, keep in mind that you are testing the string.
Using the test() Method on Literal Strings and Regular Expressions
The previous script checked a string variable for the pattern defined by a regular expression variable. It is, however, possible to check a literal string for a literal regular expression. The following snippet is identical to the previous:
/javascript/i.test("I learn JavaScript.");
If the regular expression were case-sensitive, you would simply connect the regular expression literal to the test() method with a period right after the RegExp's closing backslash:
/javascript/.test("I learn JavaScript");
Test the test() Method
Interactively test the test() method by editing the JavaScript code below and clicking the Test test() Method button.
Browser support for JavaScript test() method | |||
---|---|---|---|