Js dynamic concatenation of regular expressions in two ways

  • 2020-03-30 02:13:19
  • OfStack

Method one:

When you are working on a project, you may encounter the requirement to verify the correctness of form input with js, so you need to use js regular expressions. For example: for example to verify the month, the format is: 'yyyy-mm', this regular expression to write is very simple, really can not write out, also can Google, baidu a handful, a lot of online examples! But the fact that js regular expressions are written to death raises a new question: what if the configuration file's month format is changed? Change to 'yyyyMM', or 'yyyy_MM'... ?? Should we remember to change the regular expression in js over and over again?

At this point, we have to ask: how do you write dynamic regular expressions, modify the configuration file, and do not need to touch the code?

I looked in the js manual and couldn't find a way to convert strings to regular expressions, but I could use eval(). Method dynamically executes scripts in a way that indirectly addresses this problem! To write more general code!

The general solution of the above example is posted below:
 
 
function validateMonth(pattern, id) { 
var text = document.getElementById(id); 
var monthStr = text.value; 
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 the format. [" + pattern + "] Input! n" + "e.g "2010" + splitChar + "11" or "2010" + splitChar + "03""); 
text.value = ""; 
text.focus(); 
return false; 
} 
return true; 
} 

The same code at the page code block index 0
It is important to note that the character '\' is escaped when a script string is dynamically spelled and passed to the eval() method for execution

Method 2:
 
<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|=pattern1.test(s1); 
} 
alert(Boolean(result)); 
</script> 

Related articles: