2

I'm writing a short dynamic script piece that makes sure a URL starts with either:

  • http
  • https
  • no http/https, and merely just the // technique

And my RegExp so far:

/^(http|https|://)youtube.com|vimeo.com.*$/

So I could give it:

  • http://youtube.com
  • https://youtube.com
  • //youtube.com

... And it would work

I know it's nearly there, but how can I get it to say "http/https or just slash slash" at the beginning of the string? And then whatever comes after those URLs.

1
  • /^(https?:)?\/\/... Commented Oct 30, 2013 at 19:17

2 Answers 2

2

If you would like to know what's wrong with your regex, here's an explanation:

/^(http|https|://)youtube.com|vimeo.com.*$/

First thing's first: You need to encapsulate the youtube|vimeo part as a group (we'll add ?: to the front since we don't want to capture it). otherwise it's actually looking for (^(http|https|://)youtube.com)|(vimeo.com) which is not what you intend at all. Also, you'll want to escape your periods, since that is the dotall character (I'm assuming you do not want "youtubescom" to match), as well as your forward slashes.

Now, we have:

/^(http|https|:\/\/)(?:youtube\.com|vimeo\.com).*$/

So, here we're checking to see if "http", "https" or "://" starts a string and comes before either "youtube.com" or "vimeo.com". But, what we really want is to check if "http://", "https://" or just "//" comes before either:

/^(http:\/\/|https:\/\/|\/\/)(?:youtube\.com|vimeo\.com).*$/

You can stop there, that's your answer. However, let's continue with some cleanup by finding the redundancies. First, both our domains both have ".com", so we can make that part simply (?:youtube|vimeo)\.com. Next, our protocol prefixes all have "//", so we can pull that out to : (http:|https:)\/\/. However, now "http:" or "https:" must start the string. Since we want those to be optional, we'll add a "?" afterwards, so we get (http:|https:)?\/\/. Now, since those are so close, all we really want is that optional "s" for ssl. Finally, we can finally get:

/^(https?:)?\/\/(?:youtube|vimeo)\.com.*$/
Sign up to request clarification or add additional context in comments.

Comments

1

You can try this regex:

 /^(https?:)?\/\/(?:youtube|vimeo)\.com.*$/i

1 Comment

he wants hashes and query string too. his attempt was .*$

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.