版本号正则表达式
以数字或者字母开头,且只能包含数字、字母、空格或者(.,_ ,- )特殊字符
var testRule = /^([a-zA-Z0-9]){1}(\w|\.|-|\s*)+$/;
有个坑:
之前用
var testRule = /^([a-zA-Z0-9]){1}(\w|\.|-|\s*)+$/g;
这个判定,结果一度发现有问题,甚至怀疑人生,后来发现最后的小写“g”真的是坑死了
举个例子,这是一个测试代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>版本号</title>
</head>
<body>
<script>
//以数字或者字母开头,且只能包含数字、字母、空格或者(.,_ ,- )特殊字符
var testRule = /^(\w{1})(\w|\.|-|\s*)+$/;
//var testRule = /^(\w{1})(\w|\.|-|\s*)+$/g;
console.log("adwa===>"+testRule.test("adwa13"));
console.log("adwa===>"+testRule.test("adwa13"));
console.log("2asw===>"+testRule.test("2asw"));
console.log("2asw===>"+testRule.test("2asw"));
console.log("v3.2===>"+testRule.test("v3.2"));
console.log("v3.2===>"+testRule.test("v3.2"));
console.log("!v3.===>"+testRule.test("!v3.2"));
console.log("!v3.===>"+testRule.test("!v3.2"));
console.log("@v3.===>"+testRule.test("@v3.2"));
console.log("@v3.===>"+testRule.test("@v3.2"));
console.log("V3.2===>"+testRule.test("V3.2"));
console.log("V3.2===>"+testRule.test("V3.2"));
console.log("a3.2===>"+testRule.test("a3.2"));
console.log("a3.2===>"+testRule.test("a3.2"));
console.log("3 .2===>"+testRule.test("3 .2"));
console.log("3 .2===>"+testRule.test("3 .2"));
console.log("a3--===>"+testRule.test("a3--.2"));
console.log("a3--===>"+testRule.test("a3--.2"));
</script>
</body>
</html>
分别有两个正则表达式,一个有小g,一个没有
没有g的结果
有g的结果
可以发现,结果相差很大