我想使用 JavaScript(可以使用 jQuery)进行一些客户端验证,以检查字符串是否与正则表达式匹配:
^([a-z0-9]{5,})$
理想情况下,它将是一个返回 true 或 false 的表达式。
我是 JavaScript 新手,match()
能满足我的需要吗?似乎检查字符串的一部分是否与正则表达式匹配,而不是全部。
如果您想要的只是一个布尔结果,请使用 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')); // 真的
...并且您可以从您的正则表达式中删除 ()
,因为您不需要捕获。
使用 test()
方法:
var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
RegExp
的版本允许将变量值注入正则表达式字符串。
new RegExp("^([a-z0-9]{5,})$")
中的双引号才能使其工作
您也可以使用 match()
:
if (str.match(/^([a-z0-9]{5,})$/)) {
alert("match!");
}
但是 test()
似乎更快,因为您可以阅读 here。
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
match
成员)。如果您想将它与正则表达式一起使用(例如 String(123)
),我建议您明确地将您的号码转换为字符串。
test
的性能提高了 30%。
如果您只想知道您的字符串是否与正则表达式匹配,请使用 /youregexp/.test(yourString)
。
让 str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';让正则表达式 = /[ad]/gi; console.log(str.match(regexp));
下面是一个查找特定 HTML 标记的示例,因此很明显 /someregex/.test()
返回一个布尔值:
if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');
请记住,如果要测试整个字符串的完全匹配,请将 ^
表示为字符串的开头,将 $
表示为结尾。
例子:
/[a-z]+/.test('aaa111'); // true
/^[a-z]+$/.test('aaa111'); // false
const regExpStr = "^([a-z0-9]{5,})$" const result = new RegExp(regExpStr, 'g').test("Your string") // 这里我使用了 'g'表示全局搜索 console.log(result) // 如果匹配则为 true,否则为 false
尝试
/^[a-z\d]{5,}$/.test(str)
console.log( /^[az\d]{5,}$/.test("abc123") ); console.log( /^[az\d]{5,}$/.test("ab12") );
我建议使用 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]
你可以试试这个,它对我有用。
<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>
请试试这朵花:
/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('abc@abc.abc');
真的
如果您不希望 ^ 和 $ 围绕正则表达式(我有这样一个用例),您可以执行类似的操作
let reg = /[a-zA-Z0-9]+/g
let txt = "hello"
let matches = reg.exec(txt)[0] == txt
console.log(`It ${matches ? "does" : "doesn't"} match`)
更新/添加
如果 URL 中不存在查询字符串,则下面的解决方案将在 URL 中添加参数,如果它已经存在,那么它将更新。
function updateUrlParameter(url, param, value) {
var regex = new RegExp("(?<=[?|&])(" + param + "=)[^&]+", "i");
if (regex.test(url)) {
return url.replace(regex, param + "=" + value);
} else {
if (window.location.search) {
return `${url}&${param}=${value}`;
}else{
return `${url}?${param}=${value}`;
}
}
}
不定期副业成功案例分享