JavaScript test()Method

RegExp 对象参考手册JavaScript RegExp Object


Definition and Usage

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

If there is a matching value in the string, it returns true; otherwise, it returns false.

Syntax

RegExpObject.test(string)

Parameter Description
string Required. The string to be tested.


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the test() method


Example

Example

Search globally for the strings "Hello" and "Example" 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 "Example" patt=/Example/g; result=patt.test(str); document.write("<br>Return value:" + result);

The output result of the above example:

Return value: true
Return value: false

Try it yourself »

Example

Javascript to determine whether it is a mobile browser or a PC browser:

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

Try it yourself »


RegExp 对象参考手册JavaScript RegExp Object

Other Extensions