Javascript 检查字符串是否与 JS 中的正则表达式匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6603015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:26:35  来源:igfitidea点击:

Check whether a string matches a regex in JS

javascriptregexmatch

提问by Richard

I want to use JavaScript (can be with jQuery) to do some client-side validation to check whether a string matches the regex:

我想使用 JavaScript(可以使用 jQuery)来做一些客户端验证来检查字符串是否与正则表达式匹配:

^([a-z0-9]{5,})$

Ideally it would be an expression that returned true or false.

理想情况下,它将是一个返回 true 或 false 的表达式。

I'm a JavaScript newbie, does match()do what I need? It seems to check whether part of a string matches a regex, not the whole thing.

我是 JavaScript 新手,可以满足match()我的需求吗?它似乎检查字符串的一部分是否与正则表达式匹配,而不是整个事情。

回答by user113716

Use regex.test()if all you want is a boolean result:

使用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

...and you could remove the ()from your regexp since you've no need for a capture.

...并且您可以()从正则表达式中删除 ,因为您不需要捕获。

回答by Abhijeet Kasurde

Use test()method :

使用test()方法:

var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
    console.log("Valid");
} else {
    console.log("Invalid");
}

回答by pmrotule

You can use match()as well:

您也可以使用match()

if (str.match(/^([a-z0-9]{5,})$/)) {
    alert("match!");
}

But test()seems to be faster as you can read here.

test()似乎更快,因为您可以在这里阅读。

Important difference between match()and test():

match()和之间的重要区别test()

match()works only with strings, but test()works also with integers.

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

回答by user278064

Use /youregexp/.test(yourString)if you only want to know whether your string matches the regexp.

使用/youregexp/.test(yourString),如果你只是想知道你的字符串是否与正则表达式匹配。

回答by user2449231

Here's an example that looks for certain HTML tags so it's clear that /someregex/.test()returns a boolean:

这是一个查找某些 HTML 标签的示例,因此很明显/someregex/.test()返回一个布尔值:

if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');

回答by Eysun

 let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 let regexp = /[a-d]/gi;
 console.log(str.match(regexp));

回答by Tongi

You can try this, it works for me.

你可以试试这个,它对我有用。

 <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>

回答by Jaber Alshami

please try this flower:

请试试这朵花:

/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('[email protected]');

true

真的

回答by Kamil Kie?czewski

try

尝试

 /^[a-z\d]{5,}$/.test(str)

console.log( /^[a-z\d]{5,}$/.test("abc123") );

console.log( /^[a-z\d]{5,}$/.test("ab12") );

回答by Juan Navarrete

I would recommend using the execute method which returns null if no match exists otherwise it returns a helpful object.

我建议使用 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]