Home > Web Front-end > Front-end Q&A > What is the use of test() method in JavaScript?

What is the use of test() method in JavaScript?

青灯夜游
Release: 2021-10-09 15:37:04
Original
3968 people have browsed it

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.

What is the use of test() method in JavaScript?

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)
Copy after login
  • string Required. The string to detect.

Example:

var str = "Hello World!";
var reg = /[a-g]/g;

document.write(reg.test(str) + "<br>");             // 输出:true
Copy after login

Output result:

What is the use of test() method in JavaScript?

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);
Copy after login

Output result:

What is the use of test() method in JavaScript?

##[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template