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

154
Vistas
Ternary Operator using part of the condition as the result Javascript

In a ternary or if statement, I often want the value to equal the value of what is being tested for example

//b is a integer or '-'
//a should be an integer

const a = b === '-' ? -1 : b

The statement I am using for a is

const a = expr.match(/.*?\((.*)[a-z].*/)[1]

so it would be nice to know if there is a single line way to have it work so i'm not repeating a complicated expression that may change.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Just assign the variable first.

let b = b = expr.match(/.*?\((.*)[a-z].*/)[1];
const a = b == '-' ? -1 : b;

If you really want a one-liner, you can assign b within the expression.

const a = (b = expr.match(/.*?\((.*)[a-z].*/)[1]) == '-' ? -1 : b;

But you should have declared b earlier. You can reuse the same temporary variable every time, so you only have to declare it once and use it in all the one-liners.

If you need this pattern in multiple places, define a function.

function if_dash(expr) {
    return expr == '-' ? -1 : expr;
}

const a = if_dash(expr.match(/.*?\((.*)[a-z].*/)[1]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

If you want to get value only one time use below mentioned script. var a = (b = expr.match(/.*?\((.*)[a-z].*/)[1]) == '-' ? -1 : b;

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