Javascript 正则表达式测试()错误 : Object has no method 'test'

标签 javascript jquery regex testing

我无法让 javascript test() 方法工作,我一直收到错误,这个正则表达式在使用 match() 函数时工作正常。

这是我的 JS:

reg="^(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)(?:/)(?:watch?v=)?([^&]+)";

ytl=$('#yt').val();    //this is just an input value
if(reg.test(ytl)){
    alert('works');
}

这是我不断收到的错误:

Uncaught TypeError: 
Object ^(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)(?:/)(?:watch?v=)?([^&]+) 
has no method 'test' 

有什么想法吗?

最佳答案

test 方法定义在 RegExp 上对象。试试这个:

var reg = /^(?:https?:\/\/)?(?:www.)?(?:youtube.com|youtu.be)(?:\/)(?:watch?v=)?([^&]+)/;

或者这个:

var reg = RegExp("^(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)(?:/)(?:watch?v=)?([^&]+)");

关于Javascript 正则表达式测试()错误 : Object has no method 'test' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17689471/

相关文章:

javascript - 在PHP中使用jquery addclass和removeclass

javascript - 如何动态更改动态div的div文本

regex - 如何为 Makefile 编写 Perl 单行,以便我可以将文字\n 转换为换行符?

javascript - Node memwatch : leak of type native

javascript - JQuery 覆盖原型(prototype)中的 this 关键字

javascript - 使用 js/jquery 展开和折叠表格单元格值

jquery - Http 处理程序是合适的架构选择吗?

c# - 使用正则表达式按逻辑拆分字符串

html - 如何在 bash 中从 html 中提取 td?

javascript - 如何获取具有某个类属性的所有 HTML 元素?