preg_match 的 JavaScript 等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8088290/
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
What is the JavaScript equivalent of preg_match?
提问by Supra
Possible Duplicate:
How can i use preg_match in jQuery?
What is the jquery equivalent of the PHP preg_match feature? In PHP it would be :
什么是 PHP preg_match 特性的 jquery 等价物?在 PHP 中,它将是:
preg_match('/[^a-zA-Z0-9]/', $str);
Which checks if the string has anything other than letters and numbers. I'd like to add some client sided validation to my site, but I've looked and looked and can't quite find the jQuery equivalent of this. Thanks.
它检查字符串是否包含字母和数字以外的任何内容。我想在我的网站上添加一些客户端验证,但我看了又看,并不能完全找到与此等效的 jQuery。谢谢。
回答by jfriend00
In plain JavaScript (no jQuery needed for this), you would just use the .match()
method of the string
object which will return null
if no matches and an array if there are matches:
在纯 JavaScript 中(不需要 jQuery),您只需使用对象的.match()
方法,如果没有匹配string
则返回,null
如果有匹配则返回数组:
var str = "myteststring";
if (str.match(/[^a-zA-Z0-9]/)) {
// contains illegal characters
}
回答by John Hartsock
not jQuery but JavaScript
不是 jQuery 而是 JavaScript
var myStr = "something";
/[^a-zA-Z0-9]/.test(myStr) // will return true or false.
or for clarity
或者为了清楚起见
var regEx=/[^a-zA-Z0-9]/;
regEx.test(myStr)
The test method is part of the RegEx object... Here is some reference
测试方法是RegEx对象的一部分...这里有一些参考
回答by Dan Crews
If you want to match on a string, you can do it with vanilla JS:
如果你想匹配一个字符串,你可以用 vanilla JS 来完成:
var str = "here's my string";
var matches = str.match('/[^a-zA-Z0-9]/');
If you're trying to do it on a selector, and using jQuery, you can use:
如果您尝试在选择器上执行此操作并使用 jQuery,则可以使用:
$("div:match('/[^a-zA-Z0-9]/')")