Strange-test function of Regular Expression matching

Source: Internet
Author: User

 

In John resig's article about simple inheritance in JavascriptCode:

 
VaR fntest =/XYZ/. Test (function () {xyz ;})? /B _superb /:/.*/;

I am confused about the usage of the regular expression matching function test:

 
/XYZ/. Test (function () {xyz ;})

I checked the test function description in Mozilla Developer Center:

Executes the search for a match between a regular expression and a specified
String. returns true or false.

Whether the string contains a substring that matches the regular expression. Returns true or false.

Syntax format:

 
Regexp. Test ([STR])

Note that the parameter here is a string and it is not mentioned that the parameter of the test function can be a function.

I tried to modify this strange code and got some running results:

/XYZ /. test ("XYZ"); // true/XYZ /. test (function () {"XYZ" ;}); // false/XYZ /. test (function () {return "XYZ";}); // true/XYZ /. test (function () {return XYZ;}); // true/XYZ /. test (function () {return axyz;}); // true/XYZ /. test (function () {return "axyz" ;}); // true/XYZ /. test (function () {return "xayz" ;}); // false

What's going on?

Gorgeous split line
========================================================
I finally learned, but the type conversion was originally performed inside test. The following code:

 
/XYZ/. Test (function () {xyz ;});

It is equivalent:

 
/XYZ/. Test (function () {xyz;}). tostring ());

It is equivalent:

 
/XYZ/. Test ("function () {xyz ;}");

So why does the following code return false?

 
/XYZ/. Test (function () {"XYZ ";});

After executing this line of code, we will know:

// The execution result of this line of code is: "function () {}" (function () {" XYZ ";}). tostring ();

So we can write more weird code to confuse everyone.

 
/Function /. test (function () {}); // true // B indicates the text boundary (for English)/B _superb /. test (function () {This. _ super () ;}); // true

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.