user15484274
user15484274

Reputation:

Checking a string if it contains a link javascript

I'm trying to check if a string contains a link. And if it does contain the link return the html tag with the video or gif id.

I got it to work with youtube but i can't get it to work with giphy and was hoping maybe someone could help me.

function checkLinks(string) {
  let youtubeId = (string.match(/youtube\.com\/watch\?.*?v=([^&]+)/i) || [])[1];

  if (youtubeId)
    return '<div class="videoDiv"><iframe width="500" height="281.25" src="https://www.youtube.com/embed/' + youtubeId + '" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>';

  let gifID = (string.match(/media4\.giphy\/.com\/media\?.*([^&]+)/i) || [])[1];

  if (gifID)
    return '<div class="gifDiv"><a href="https://media4.giphy.com/media/' + gifID + '/giphy.gif" class="fancybox"><img class="chat_image" src="https://media4.giphy.com/media/'+ gifID + '/100.gif"></a></div>'

  return '';
}

const checkGif = checkLinks('https://media4.giphy.com/media/jQyHHXQ60W93O/giphy.gif');
const checkYoutube = checkLinks('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
console.log('check gif', checkGif);
console.log('check youtube', checkYoutube);

Upvotes: 2

Views: 99

Answers (1)

mplungjan
mplungjan

Reputation: 177688

Here is something less complicated

function checkLinks(string) {
  const url = new URL(string), hostname = url.hostname;
  if (hostname.includes("youtube")) {
    const youtubeId = url.searchParams.get("v")
    return '<div class="videoDiv"><iframe width="500" height="281.25" src="https://www.youtube.com/embed/' + youtubeId + '" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>';
  } else if (hostname.includes("giphy")) {
    const gifID = url.pathname.split("\/")[2];
    return '<div class="gifDiv"><a href="https://media4.giphy.com/media/' + gifID + '/giphy.gif" class="fancybox"><img class="chat_image" src="https://media4.giphy.com/media/' + gifID + '/100.gif"></a></div>'
  }

  return '';
}

const checkGif = checkLinks('https://media4.giphy.com/media/jQyHHXQ60W93O/giphy.gif');
const checkYoutube = checkLinks('https://www.youtube.com/watch?v=dQw4w9WgXcQ');
console.log('check gif', checkGif);
console.log('check youtube', checkYoutube)

Upvotes: 1

Related Questions