This article mainly introduces the two methods of JS dynamic splicing regular expression, the need friend can refer to the following
Method a: do project when you may encounter with JS validation form input Correctness of the demand, this time need to use the regular expression of JS. For example: To verify the month, the format is: ' yyyy-mm ', this regular expression is very simple to write, it can not write, but also Google, Baidu, a lot of online examples! But the JS regular expression is written to death will also bring a new problem: if the format of the month of the configuration file changed? Change to ' yyyymm ', or ' yyyy_mm ' ... ?? Do we have to remember to go to the regular expression in JS also followed over and over again to change it?? At this time we will ask: how to write a dynamic regular expression, modify the configuration file, you do not need to move the code? I went through the JS manual, did not find a way to convert the string into a regular expression, but can use the eval () method to dynamically execute the script to solve this problem indirectly! To write more general code! Post the generic solution for the above example: code as follows:/** * Verify that the month form input is valid * Pattern: Month format string * ID: Form id */ function Validatemonth (pattern, id) { var text = document.getElementById (id); var monthstr = Text.val ue; var Splitchar = ""; if (Pattern.length > 6) Splitchar = pattern.substring (4, pattern.length-2); Eval ("var re =/d{4}" + Splitchar + "d{2}$/;"); //var re =/d{4}-d{2}$/; if (monthstr.match (RE) = null) { alert ("Please refer to format [+ pattern +]" input!) n "+" e.g "+ Splitchar +" one "or" "+ Splitchar +" ""); Text.value = ""; teXt.focus (); return false; } true; } code is as follows:/** * Verify that the month form entry is legal   ; * Pattern: Month format string * ID: Form id */ function validatemonth ((pattern, id) { var text = Document.getel Ementbyid (ID); var monthstr = text.value; var Splitchar = ""; if (Pattern.length > 6) Splitchar = Patt Ern.substring (4, pattern.length-2); eval ("var re =/d{4}" + Splitchar + "d{2}$/;"); //var re =/d{4}-d{2}$/; if (monthstr.match (RE) = null) { alert ("Please refer to format [+ pattern +]" input!) n "+" e.g "+ Splitchar +" one "or" "+ Splitchar +" ""); Text.value = ""; text.focus (); retur N false; } return true; } One thing to note: dynamically spelling out script strings passed to the Eval () method executes, requires the character ' escape method two: Code as follows: <script> var n=new Array (". htm", ". html", ". shtml"); //var pattern1 = new RegExp ( "w+" +n[0]+ "$", "GI"); var s1= "b.shtml"; var result = FAlse; for (var i=0;i <n.length;i++) { pattern1 = new RegExp ("w+" +n[i]+ "$", "GI"); Result|=pa Ttern1.test (S1); } alert (Boolean result); </script>