4

I cant get the javascript test() method to work, I keep getting an error, this regular expression is working 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 keep getting:

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

Any ideas?

0

1 Answer 1

8

The test method is defined on RegExp objects. Try this:

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

Or this:

var reg = RegExp("^(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)(?:/)(?:watch?v=)?([^&]+)");
Sign up to request clarification or add additional context in comments.

1 Comment

Interesting, so much to learn with JavaScript, when I have no issues with PHP, seems so much more finicky, just my inexperience however. That works perfectly, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.