Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda