Easy Tutorial
❮ Met Element Removeeventlistener Prop Doc Lastmodified ❯

JavaScript test() Method

JavaScript RegExp Object


Definition and Usage

The test() method is used to test whether a string matches a pattern.

It returns true if a match is found in the string, otherwise it returns false.

Syntax

Parameter Description
string Required. The string to be tested.

Browser Support

All major browsers support the test() method.


Examples

Search globally for "Hello" and "tutorialpro" in a string:

var str = "Hello world!";
// Search for "Hello"
var patt = /Hello/g;
var result = patt.test(str);
document.write("Return value: " + result); 
// Search for "tutorialpro"
patt = /tutorialpro/g;
result = patt.test(str);
document.write("<br>Return value: " + result);

The above example outputs:

Return value: true
Return value: false

Example

Determine if the browser is a mobile or PC browser:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
    document.write("Mobile");
} else {
    document.write("PC");
}

JavaScript RegExp Object

❮ Met Element Removeeventlistener Prop Doc Lastmodified ❯