Add a variable to the Regular Expression in JS

Source: Internet
Author: User

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 ")

Related Article

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.