Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
How to include a condition inside a string using Javascript

I know for singular results, I can do something like this:

return "this is a condition test within a string - " +  {0:'⚪',1:'🟡',2:'🔴',3:'&#x1f7e2',8:'',9:''}[event.FlagInd.toString()]

where 0, 1, 2 etc are values from the variable event.FlagInd, and the results are the values inside the quoted strings such as '⚪' etc

So in the example above, a value of 1 in the event.FlagID, replaces the 1 with 🟡 - a yellow ball

I am trying to do something similar, to "turn on or off" actual HTML inside a string.

My current attempts return invalid strings or the strings are not formed correctly.

 return
        "<strong style=\"font-size:18px;\">" +
        {
            0: '', default: "<a href=\" + "https://www.marinetraffic.com/en/ais/details/ships/imo:" + event.imo +
                "/vessel:" + event.text + "\" target=\"_blank\">" + event.text + "</a>"' }[event.imo.toString()] +
            "</strong>" + ... etc

What I am trying to do is return an empty string if the value of event.IMO = 0, but to return this entire html string, if the value is something other than 0 ...

"<a href=\"https://www.marinetraffic.com/en/ais/details/ships/imo:" + event.imo + "/vessel:" + event.text + "\" target=\"_blank\">" + event.text + "</a>"
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Thanks to @Ouroborus, I was able to do it... as per this example:

function myResult(IMO, text){
     return "Answer is " + 
        (IMO.toString() == 0 ? "nothing here" :
      "<strong style=\"font-size:18px;\">" +
      "<a href=\"https://www.marinetraffic.com/en/ais/details/ships/imo:" + IMO +
      "/vessel:" + text + "\" target=\"_blank\">" + text + "</a>" + 
      "</strong>")
}
 
document.write(myResult("0123","myShip"))

Changing the value from "0123" to "0" gives me the "nothing here", otherwise it's the HTML entirely. Just got to make sure you format the HTML as a string correctly.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda