Detect and Validate YouTube URL with JavaScript RegExp -
Detect and Validate YouTube URL with JavaScript RegExp
by on on other

Detect and Validate YouTube URL with JavaScript RegExp

JAVASCRIPT IF LINK IS A YOUTUBE LINK

how to know if a URL is a YouTube video link. here is a common solution we can use to do that using JavaScript regular express or regexp.

export const videoHelper = (url) => {

  const isYoutube = validateYouTubeUrl(url);

  return `<video controls class="video" id="video" preload="metadata" 
          poster="https://images.pexels.com/photos/5596125/pexels-photo-5596125.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940">
              <source src="https://www.youtube.com/watch?v=RXE1uqN3qzQ" type="${
                isYoutube ? `text/html` : ``
              }"></source>
          </video>`;
};

function validateYouTubeUrl(urlToParse) {
  if (urlToParse) {
    var regExp = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
    if (regExp.test(urlToParse)) return true;
  }
  return false;
}