Javascript 包含一个正则表达式引擎,可通过string.match()、string.replace()和string.split()函数访问。
例如:
var mystring = "this is a sentence";
mystring = mystring.replace(/sentence/,'string');
var matches = mystring.match(/\b\w+\b/);
这应该为您提供与preg_match().
因此,要在您的问题中进行与 preg_match 相同的验证:
if(!phone.val().match(/^[0-9]{3}-|\s[0-9]{3}-|\s[0-9]{4}$/)) {
phone.addClass("needsfilled");
phone.val(phonerror);
}
如果您绝对坚持使用preg_match()与 PHP 版本完全相同的函数调用,那么有一个名为PHPJS的项目,旨在用 Javascript 实现 PHP 函数。快速浏览一下他们的网站会发现,尽管他们目前还没有完全可用的preg_match()实现,但他们有一个未完成的实现,您可能想看看。但坦率地说,内置的 Javascript.match()功能应该绰绰有余。