user225269
user225269

Reputation: 10913

Matching a specific url in javascript

I'm trying to match youtube and vimeo urls on javascript. I'm using regexr to play around and came up with this:

(http|https)://(youtu|www.youtube|vimeo|youtube)\.(be|com)/[A-Za-z0-9\?&=]+

It works pretty well on regexr, whitespaces aren't included in the match so it would only match this:

http://youtu.be/ssdfsjlfsfsl

And not this:

http://youtu.be/ssdfsjl someword

But when I test it out on javascript it still matches the url with a whitespace and another word beside it:

var x = new RegExp("(http|https)://(youtu|www.youtube|vimeo|youtube)\.(be|com)/[A-Za-z0-9\?&=]+")

x.test("http://www.youtube.com/watch?v=FvYo3ZgaQ1c&feature=plcp someword")

Not sure why this is happening, I've also tried adding \S or !\s but it doesn't seem to have any effect.

Upvotes: 1

Views: 2462

Answers (3)

jbabey
jbabey

Reputation: 46647

regex.test(string) returns a boolean value of whether one or more matches are found in the string, so it would (and should) return true for "http://www.youtube.com/watch?v=FvYo3ZgaQ1c&feature=plcp someword".

If you want to test that your string is a URL and ONLY a url, add some anchors:

^(http|https)://(youtu|www.youtube|vimeo|youtube)\.(be|com)/[A-Za-z0-9\?&=]+$

Upvotes: 2

Andrew Cheong
Andrew Cheong

Reputation: 30273

It's because you haven't anchored your expression.

^(http|https)://(youtu|www.youtube|vimeo|youtube)\.(be|com)/[A-Za-z0-9\?&=]+$
|                                                                           |
here, and...                                                                here.

Upvotes: 1

Ross McLellan
Ross McLellan

Reputation: 1881

Doesn't look like you're checking for the start / end of the string. Using ^ and $

var x = new RegExp("^(http|https)://(youtu|www.youtube|vimeo|youtube)\.(be|com)/[A-Za-z0-9\?&=]+$")

Upvotes: 2

Related Questions