Categories
JavaScript Answers

How to Validate YouTube URL with JavaScript Regexes?

Spread the love

To validate YouTube URL with JavaScript regexes, we can use the following regex:

/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/

^ marks the start of the string.

(?:https?:\/\/)? checks for the protocol.

(?:www\.)? checks for the www part of the URL.

(?:youtu\.be\/|youtube\.com\/ checks for the youtube.com or youtub.be URLs.

(?:embed\/|v\/|watch\?v=|watch\?.+&v=) checks for the embed, watch, and v query strings.

((\w|-){11}) checks if the v query parameter value is 11 characters long.

(?:\S+)?$ checks for spaces at the end of the string.

Since the url is a valid YouTube URL, the console log should log true.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *