1

I would like to know how I can check if a url with a certain file has the pdf extension, in my code if the url has a pdf file a modal will be opened, if it is any other extension nothing happens.

I tried doing this using: if (/pdf/.test(document.file))

As document.file the link from my file.

But something is wrong, maybe the syntax of the code I should be confused with the + and the "" in the html part.

My code is:

for(var key in data.val()){
    documento = data.val()[key]
    linha = "<tr>"+
    "<td>"+documento.titulo+"</td>"+
    "<td>"+documento.data_inicio+"</td>"+
    "<td>"+documento.categoria+"</td>"+
       if (/pdf/.test(documento.arquivo)){+
           "<td class='view'><a data-toggle='modal' data-target='#myModal' data-link='"+documento.arquivo+"'><i class='fa fa-eye'></i></a></td>"+
        }+
        "</tr>";

        $('#tableCustom tbody').append(linha);  
        $(".view a").on( "click", function() {
            var link = $(this).data('link');
            PDFObject.embed(link, ".modal-content");
        });                         
}
Denis Policarpo
  • 153
  • 2
  • 12
  • It looks like you are trying to concatenate an if statement into your string. That is all sorts of broken... check out the ternary operator as a alternative to you if... – Rob C Dec 24 '17 at 22:15
  • try to change `/pdf/` with `/\.pdf$/` https://regex101.com/r/2TTWBQ/1 – plonknimbuzz Dec 24 '17 at 22:21

2 Answers2

3

You can use .indexOf() and that would tell you if there is a ".pdf" in the url

if (documento.arquivo.indexOf(".pdf") != -1) {
    // It is a pdf 
}
Mason Wright
  • 357
  • 1
  • 3
  • 11
1

You cannot use the if statement inside string concatenation. So it is a syntax error.

What you could do:

  • Create variable, which holds an empty string
  • Use the .indexOf() method like @Mason Wright suggested.
  • If it has the pdf extension build your string by using the newly created variable
  • Use the variable in string concatenation.
Andreas
  • 431
  • 2
  • 13