JavaScript test() Method
Definition and Usage
The test() method is used to check whether a string matches a certain pattern.
If there is a matching value in the string, it returns true; otherwise false.
Syntax
RegExpObject.test(
string
)
| Parameters | Description |
|---|---|
| string | Required. The string to be tested. |
Browser support





All major browsers support the test() method.
Example
Example
Search globally in the string for "Hello" and "Runoob":
var
str
=
"
Hello world!
"
;
//
Find "Hello"
var
patt
=/
Hello
/
g
;
var
result
=
patt
.
test
(
str
)
;
document
.
write
(
"
Return value:
"
result
)
;
//
Search for "Runoob"
patt
=/
Runoob
/
g
;
result
=
patt
.
test
(
str
)
;
document
.
write
(
"
Return value:
"
result
)
;
The output of the above example is:
Return value: true
Return value: false
Try it »
Example
Javascript: Detect 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 »
JavaScript RegExp Object