Test function of regular matching

Time:2021-7-22

var fnTest = /xyz/.test(function(){xyz;}) ? / b_ superb/ : /.*/; I am very confused about the usage of the regular expression matching function test
/xyz/.test(function(){xyz;}) I looked up the description of the test function in Mozilla Developer Center
Executes the search for a match between a regular expression and a specified string. Returns true or false.
Whether there are substrings in the string that match the regular expression. Returns true or false.
Its syntax format is as follows:
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 at all.
I try to modify this strange code and get some running results

Copy codeThe code is as follows:
/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”;}); // What’s wrong with false?

Gorgeous dividing line
=======================================
I finally know, but I converted the type inside the test. The following code:

Copy codeThe code is as follows:
/xyz/.test(function(){xyz;});

Equivalent to:

Copy codeThe code is as follows:
/xyz/.test((function(){xyz;}).toString());

It is also equivalent to:

Copy codeThe code is as follows:
/xyz/.test(“function(){xyz;}”);

So why does the following code return false?

Copy codeThe code is as follows:
/xyz/.test(function(){“xyz”;});

Let’s execute this line of code

Copy codeThe code is as follows:
//The execution result of this line of code is: “function () {}”
(function(){“xyz”;}).toString();

So we can write more weird code to confuse you

Copy codeThe code is as follows:
/function/.test(function(){}); // true
//B is the word boundary (for English)
/b_superb/.test(function(){this._super();}); // true

Recommended Today

What should I do to become a full stack engineer?

Introduction: how to become a full stack engineer? What technical accumulation is required? What are the benefits of being a full stack engineer? I hope this article can provide some help for students who hope to become engineers of the whole stack and share with them. As developers, we don’t excessively distinguish between server and […]