Home >Web Front-end >Front-end Q&A >What is the use of test() method in JavaScript?
In JavaScript, the test() method is used to test whether a string matches a regular expression. The syntax is "RegExpObject.test(string)". If it matches, it returns true, if it does not match, it returns false.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
JavaScript string is the most commonly used data type in programming. String operations need to be performed in many places, such as determining whether a string is a legal email address and intercepting from a string. designated parts, etc.
Regular expression is a kind of logical formula used to match strings or special characters. The so-called logical formula is composed of some specific characters and is used to represent special strings of certain rules. You can Express filtering logic for string data.
The test() method in JavaScript can test whether a string matches a regular expression. If it matches, it returns true, if it does not match, it returns false.
Syntax:
RegExpObject.test(string)
string Required. The string to detect.
Example:
var str = "Hello World!"; var reg = /[a-g]/g; document.write(reg.test(str) + "<br>"); // 输出:true
Output result:
Explanation:
Call the test() method of the RegExp object r and pass it the string s, which is equivalent to this expression: (r.exec(s) != null).
Example:
var str="Hello world!"; //look for "Hello" var patt=/Hello/g; var result=patt.test(str); document.write("Returned value: " + result); //look for "world" patt=/world/g; result=patt.test(str); document.write("<br>Returned value: " + result); //look for "php" patt=/php/g; result=patt.test(str); document.write("<br>Returned value: " + result);
Output result:
##[Recommended learning:javascript advanced tutorial]
The above is the detailed content of What is the use of test() method in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!