Check if input value contains specific word, using jQuery

Asked

Viewed 108 times

0

I’m creating a function to take the youtube link written in an input and take the image of this video.

To get the image just use the link below, changing the video id (value v=) by youtube link:

Link do video
https://www.youtube.com/watch?v=99s-xZhZNns

Imagem:
<img src="https://img.youtube.com/vi/99s-xZhZNns/mqdefault.jpg">

For this I created the function below, but I wanted to create a rule so that it would create the image only if the text of the input has the term "youtube.com/watch? v=" to prevent it from creating an image with wrong reference, if it does not have the term, a message should appear (Link not found)

<input type="text" id="youtube">
<span id="thumb"></span>

<script>
$( "#youtube" ).keyup(function() {
    //verificar se #youtube contem o termo ".youtube.com/watch?v="
    //SE TIVER pegar o valor de v= e montar a imagem
    $("#thumb").html('<img src="https://img.youtube.com/vi/valor_do_v=/mqdefault.jpg">');
});
</script>

1 answer

2


You can use a condition for this by using the method indexOf.

Something like that:

$('#youtube').on('change', function() {
  var value = $(this).val()

  if (value.indexOf('.youtube.com/watch?v=') === -1) {
    alert('Não tem.')

    // Usamos o "return" para parar a execução da função de callback.
    return
  }

  alert('Tudo certo! Faça o que você precisa fazer aqui.')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="youtube" />
<span id="thumb"></span>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.