Wen
Wen

Reputation: 519

Youtube links not matching regex correctly

This is my code:

$(document).ready(function(){

    var valid_url = new RegExp('http://[www\.]?youtube.com/watch\?v=[a-zA-Z0-9_-]*', '');

    $('a').each(function(){

        // Check if it's a valid Youtube URL
        var link = $(this).attr('href');
        if( valid_url.test( link ) ){
            alert( "valid" );
        }

    });

});

But it doesn't seem to match the Youtube URL's correctly. I think it's the way I'm trying to match it using regex. I've tested the regex itself multiple ways and it is indeed correct, but I'm not familiar with using regex with Javascript so might be using it incorrectly.

Any help is appreciated, thanks.

Upvotes: 2

Views: 392

Answers (1)

John Kugelman
John Kugelman

Reputation: 361625

Use parentheses around the www., not square brackets. Square brackets are for character classes. [www\.] is the same as [w.] and means "match a single w or literal .", not exactly what you intend.

Also, the literal dash you have at the end of the regex needs to be escaped.

http://(www\.)?youtube.com/watch\?v=[a-zA-Z0-9_\-]*

Upvotes: 3

Related Questions