项目框架把JavaScript脚本存入数据库,展示页面的时候从数据库读取字段拼接页面。正则表达式取出来[\]都变成了双反斜杠【\\】,
A写法改成B写法后问题解决。因为数据库是把整个js脚本当成字符串存储的,这种时候,正则表达式不能写成A的方式,要改成B就可以了。
A:pattern = /^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])){3}$/g;
B:pattern =new RegExp('^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])){3}$');
<html>
<head></head>
<body onload='test();'>
<script>
function test2(){
var ipstr='1.1.1.1';
var array=[];
array.push(ipstr);
var pattern =new RegExp('^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])){3}$');
//pattern = /^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9])){3}$/g;
alert(pattern.test(array[0]));
}
function test(){
var ipstr='1.1.1.1/5,1.1.1.8,1.1.1.9999';
var pattern =/^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$/g;
var ipArray = ipstr.split(',');
var ipArrayTotal = [];
for(var i=0;i<ipArray.length;i++){
if(ipArray[i].indexOf('/')<0){
alert(ipArray[i]);
ipArrayTotal.push(ipArray[i]);
}else{
var ip1=ipArray[i].substring(0,ipArray[i].indexOf('/'));
var ip2 = ip1.substring(0,ip1.lastIndexOf('.')+1)+ipArray[i].substring(ipArray[i].indexOf('/')+1,ipArray[i].length);
ipArrayTotal.push(ip1);
ipArrayTotal.push(ip2);
alert(ip1+":"+ip2);
}
}
for(var i=0;i<ipArrayTotal.length;i++){
debugger;
//alert(pattern.test('1.1.1.1'));
pattern.lastIndex = 0;
if(pattern.test(ipArrayTotal[i])){
alert('匹配');
//alert(pattern.test(ipArrayTotal[i]));
}else{
alert("用户自带互联IP格式不合法,请重新输入");
return;
}
}
}
</script>
</body>
</html>
来源:https://www.cnblogs.com/ccf0537/p/10429304.html