Javascript regex test (): Object does not have a 'test' method

I can’t get the javascript test() method to work, I keep getting an error, this regular expression works fine when using the match() function.

This is my 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'); } 

This is the error I get:

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

Any ideas?

+4
source share
1 answer

The test method is defined on RegExp objects. Try the following:

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

Or that:

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

Source: https://habr.com/ru/post/1491751/


All Articles