js正则表达式,不能以/开始和结尾的示例代码:
var re = /^([^\/]([\s\S]*[^\/])?)?$/;
var cases = [
[“”, true],
[” “, true],
[“a”, true],
[“abc”, true],
[“a/c”, true],
[” /b/ “, true],
[“/”, false],
[“/bc”, false],
[“ab/”, false],
[“/b/”, false],
[“//”, false]
];
var i, err=false;
for(i=0; i<cases.length; i++){
if(re.test(cases[i][0]) !== cases[i][1]){
err=true;
alert(“fail: “+cases[i].join(“,”));
}
}
if(!err){
alert(“pass”);
}
用两个正则来干这件事,简单明了:
var test = function(str){
if(/^\//.test(str) || /\/$/.test(str)){
return false;
}
return true;
};
var cases = [
[“”, true],
[” “, true],
[“a”, true],
[“abc”, true],
[“a/c”, true],
[” /b/ “, true],
[“/”, false],
[“/bc”, false],
[“ab/”, false],
[“/b/”, false],
[“//”, false]
];
var i, err=false;
for(i=0; i<cases.length; i++){
if(test(cases[i][0]) !== cases[i][1]){
err=true;
alert(“fail: “+cases[i].join(“,”));
}
}
if(!err){
alert(“pass”);
}
写的不错真的不错