Recently, my colleague asked me how to add variables to the Regular Expression in js, and wrote a blog record. I. Literally, when we define a string, an array, an object, and so on, we are used to defining it with a literal, for example: var s = "string "; var a = [1, 2]; var o = {}; it is also very simple to add variables, such as var v = "bl "; var s = "string" + v; // "stringbl" var a = [1, v]; // [1, "bl"] var o = {first: v}; // {first: "bl"}. However, if you use a regular expression, it seems that everything is not as good as that. Var v = "bl"; var re =/^ \ d + $/gim; then, if you want to add the v variable to \ d +, you will find that, no way. Because no matter how you write it, it will be processed as part of the regular expression. 2. constructors are in the JS world. Except null, undefined. The rest are objects. However, it must be said that how can string, number, and boolean be objects. In fact, although the above sentence is not accurate, it is indeed the most intuitive feeling. Because when you use string, number, and boolean, the corresponding BASIC packaging type is converted to an object by default. Then we know that in JS, all objects are generated by constructors. Then, we can use constructors to replace the literal definition method, for example, var s = new String ("string"); // String object, toString () followed by "string" var a = new Array (); // [] var o = new Object, you can also use the constructor to generate the regular expression var re = new RegExp ("^ \ d + $", "gim"); // note that the backslash must be escaped, adding a variable to the string is the same as adding a variable to the string we wrote earlier. Var v = "bl"; var re = new RegExp ("^ \ d +" + v + "$", "gim "); // re is/^ \ d + bl $/gim, and the initial problem is completely solved. In addition, there is another way to use eval to dynamically execute a string, but I think it is a best practice in all aspects. Var re = eval ("/^ \ d +" + v + "$/gim ")