Ric*_*ard 663 javascript regex match
我想使用JavaScript(可以使用jQuery)进行一些客户端验证来检查字符串是否与正则表达式匹配:
^([a-z0-9]{5,})$
Run Code Online (Sandbox Code Playgroud)
理想情况下,它将是一个返回true或false的表达式.
我是一个JavaScript新手,确实match()
做我需要的东西?它似乎检查字符串的一部分是否匹配正则表达式,而不是整个事物.
use*_*716 1074
使用regex.test()
,如果你想要的是一个布尔结果:
console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true
Run Code Online (Sandbox Code Playgroud)
...而且你可以()
从正则表达式中删除它,因为你不需要捕获.
Abh*_*rde 161
使用test()
方法:
var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
Run Code Online (Sandbox Code Playgroud)
pmr*_*ule 85
你也可以使用match()
:
if (str.match(/^([a-z0-9]{5,})$/)) {
alert("match!");
}
Run Code Online (Sandbox Code Playgroud)
但test()
似乎更快,因为你可以在这里阅读.
match()
和之间的重要区别test()
:
match()
仅适用于字符串,但test()
也适用于整数.
12345.match(/^([a-z0-9]{5,})$/); // ERROR
/^([a-z0-9]{5,})$/.test(12345); // true
/^([a-z0-9]{5,})$/.test(null); // false
// Better watch out for undefined values
/^([a-z0-9]{5,})$/.test(undefined); // true
Run Code Online (Sandbox Code Playgroud)
这是一个查找某些HTML标记的示例,因此很明显/someregex/.test()
返回一个布尔值:
if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');
Run Code Online (Sandbox Code Playgroud)
小智 7
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));
Run Code Online (Sandbox Code Playgroud)
尝试
/^[a-z\d]{5,}$/.test(str)
Run Code Online (Sandbox Code Playgroud)
/^[a-z\d]{5,}$/.test(str)
Run Code Online (Sandbox Code Playgroud)
小智 7
我建议使用execute方法,如果不存在匹配则返回null,否则它返回一个有用的对象。
let case1 = /^([a-z0-9]{5,})$/.exec("abc1");
console.log(case1); //null
let case2 = /^([a-z0-9]{5,})$/.exec("pass3434");
console.log(case2); // ['pass3434', 'pass3434', index:0, input:'pass3434', groups: undefined]
Run Code Online (Sandbox Code Playgroud)
小智 6
你可以试试这个,它对我有用。
<input type="text" onchange="CheckValidAmount(this.value)" name="amount" required>
<script type="text/javascript">
function CheckValidAmount(amount) {
var a = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
if(amount.match(a)){
alert("matches");
}else{
alert("does not match");
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
719054 次 |
最近记录: |